javascript - 如何检查字符串或html中是否有相同的连续元素

标签 javascript jquery

假设我有这个字符串

<div id="ch">abcdefg<img /><img />hij</div>
<div id="ad">abc<img />defg<img />hij</div>

strHtml = $('div#ch').html();
strHtmlFalse = $('div#ad').html();

现在有一种可能的方法来检查是否找到两个“img”元素以及它们是否是连续的 sibling 。

chConImg = checkConsecutiveImg(strHtml) //true
chConImgFalse = checkConsecutiveImg(strHtmlFalse) //false


checkConsecutiveImg(str){
    if(consecutive img elements are found)
        return true;
    else
        return false;
}

最佳答案

普通 Javascript 方法

function checkConsecutiveImage(str) {
  const parent = document.querySelector(str);
  const children = parent.children;
  const image = Array.from(children).find(elem => elem.tagName === 'IMG');
  
  return image.nextSibling.nodeType === 1 && image.nextElementSibling.tagName === 'IMG'
}

console.log(`Consecutive images in #ch: ${checkConsecutiveImage('#ch')}`);

console.log(`Consecutive images in #ad: ${checkConsecutiveImage('#ad')}`);
<div id="ch">abcdefg<img /><img />hij</div>
<div id="ad">abc<img />defg<img />hij</div>

jQuery 方法

$(function() {
  function checkConsecutiveImg(str) {
    const $img = $(str).find('img');
    
    return $img[0].nextSibling.nodeType === 1 && $img.next().is('img');
  }

  console.log(`Consecutive images in #ch: ${checkConsecutiveImg('#ch')}`);

  console.log(`Consecutive images in #ad: ${checkConsecutiveImg('#ad')}`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="ch">abcdefg<img /><img />hij</div>
<div id="ad">abc<img />defg<img />hij</div>

关于javascript - 如何检查字符串或html中是否有相同的连续元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41001246/

相关文章:

javascript - Sharepoint 文档库 - 使用 javascript 将文件名命名为标题

javascript - 使用 cookie 记住背景颜色并在从表单访问时显示它

javascript - 如何在 10 秒后调用 ajax 并且我的页面每秒加载一次

javascript - 从 1 d3.select 隐藏另一个 div

javascript - 使用 Jquery 拖放

javascript - 当字符串中存在分割字符时分割函数

javascript - typescript 多态性

javascript - 将 div 在带有叠加层的页面上居中

javascript - 如何在 javascript 中使用嵌套函数作为生成器(使用 "inner"产量)

jQuery 1.4.2 VSDoc