获取childNodes的内容

时间:2018-08-16 09:29:24

标签: javascript jquery

我有一个如下的HTML结构。我需要获取标题内容和描述内容。

<div id="results">
    <div class="ui list">
        <div class="item">
            <div class="content">
                <a class="header" onclick=" toMaker(event, 967)">Mahachai Holding</a>
                <div class="description">Lat Phrao, Bangkok, 10230</div>
            </div>
        </div>
    </div>
</div>

我使用了以下代码

$('#results > .ui.list')[0].childNodes[0].childNodes[1].innerHTML

获取类似

的字符串

"<a class="header" onclick=" toMaker(event, 967)">MahachaiHolding</a><div class="description">Lat Phrao, Bangkok, 10230</div>"

但是现在我对如何获取标题名称和描述名称感到困惑?

4 个答案:

答案 0 :(得分:2)

您需要找到.html().header中的.description

const $content = $("#results .ui.list .item .content");
console.log($content.find(".header").html());
console.log($content.find(".description").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="results">
  <div class="ui list">
    <div class="item">
      <div class="content">
        <a class="header" onclick=" toMaker(event, 967)">Mahachai Holding</a>
        <div class="description">Lat Phrao, Bangkok, 10230</div>
      </div>
    </div>
  </div>
</div>

答案 1 :(得分:1)

$('#results > .ui.list')[0].childNodes[0].childNodes[1].innerHTML

$('#results > .ui.list').find('.header') //will get you header element
$('#results > .ui.list').find('.description') //will get you description element

这是你的意思吗?

https://api.jquery.com/find/

参考网址

答案 2 :(得分:0)

尝试一下...

  

输出将仅给出元素的文本,而不是内部html

/// Get the header text 
console.log($('#results .ui.list a.header').text());

/// Get the description text 
console.log($('#results .ui.list div.description').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="results">
  <div class="ui list">
    <div class="item">
      <div class="content">
        <a class="header" onclick=" toMaker(event, 967)">Mahachai Holding</a>
        <div class="description">Lat Phrao, Bangkok, 10230</div>
      </div>
    </div>
  </div>
</div>

答案 3 :(得分:0)

尝试一下...

 <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        console.log($(".content").text())
    });
    </script>
    </head>
    <body>

    <div id="results">
        <div class="ui list">
            <div class="item">
                <div class="content">
                    <a class="header" onclick=" toMaker(event, 967)">Mahachai Holding</a>
                    <div class="description">Lat Phrao, Bangkok, 10230</div>
                </div>
            </div>
        </div>
    </div>

    </body>
    </html>