как найти последний текстовый узел элемента <p>? - PullRequest
0 голосов
/ 25 октября 2019

в следующем фрагменте кода мне нужно получить текстовый узел, который является последним дочерним элементом.

<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">
        <b>The value conclusion of the Income Approach</b>
     </font>
    </font>
  </font>
</p>

Мне нужно выбрать текстовый узел The value conclusion of the Income Approach, доступным является только <p>, элементы внутри тега <p> являются динамическими.

это еще один html.

<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000"><font face="Arial, serif">
    <font size="1" style="font-size: 8pt">The client has specifically....</font>
 </font>
</p>

В приведенном выше фрагменте мне нужно выбрать The client has specifically....

код, который я пробовал

var $html = `<div>
                            <p class="western" style="margin-bottom: 0.14in">
                              <font color="#000000"><font face="Arial, serif">
                                <font size="1" style="font-size: 8pt">The client has specifically....</font>
                             </font>
                            </p>
                            <p class="western" style="margin-bottom: 0.14in">
                                <font color="#000000"><font face="Arial, serif">
                                    <font size="1" style="font-size: 8pt">The client has specifically....</font>
                                </font>
                            </p>
                        </div>`;

                $html.find('p').each(function(){

                    $(this).contents().filter(function(){
                        return this.nodeType === 3; // Text node
                    }).each(function(){

                        var f = $(this).parent().css('font-size');

                        if(f && f.trim() != '')
                            $(this).closest('p').css('font-size', f);
                    });                    
                });

Я хочу назначить такой же размер шрифта <p>элемент собственным текстовым узлом

Ответы [ 4 ]

0 голосов
/ 25 октября 2019

Предполагая, последний дочерний элемент является последним элементом, не имеющим дочерних узлов, вы можете сделать это:

$(function() {
  $("p").each(function() {
    var $lastelem = $(this).find("*").filter(function() {
      // count children instead of childNodes
      return this.children.length === 0;
    }).last();
    console.log(this, $lastelem.get(0), $lastelem.css("font-size"));
  });
});
<!--
WARNING: enabling stacksnippets console causes this
script to stall. Do not enable "show console", look
at your browser's console instead.
-->

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">
        <b>The value conclusion of the Income Approach</b>
      </font>
    </font>
  </font>
</p>

<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">The client has specifically....</font>
    </font>
  </font>
</p>
0 голосов
/ 25 октября 2019

Вы можете получить текст просто $('.western').find('*').last().text()

0 голосов
/ 25 октября 2019

Посмотрите, поможет ли вам этот маленький код.

var $target = $('p.western').children();

while ($target.length) {
    $target = $target.children();
}

console.log($target.end().text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">
        <b>The value conclusion of the Income Approach</b>
     </font>
    </font>
  </font>
</p>

var $target = $('p.western').children();

while ($target.length) {
    $target = $target.children();
}

console.log($target.end().text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000"><font face="Arial, serif">
    <font size="1" style="font-size: 8pt">The client has specifically....</font>
 </font>
</p>
0 голосов
/ 25 октября 2019

Вы можете использовать строку селектора, чтобы найти все элементы с атрибутом style, которые являются потомками p. Убедитесь, что атрибут имеет font-size и что-то находится внутри элемента, затем вернитесь к p:

$('p [style]')
  .each(function() {
    const $this = $(this);
    if ($this.text().trim()) {
      const fontSize = $(this).css('font-size');
      if (fontSize.trim()) {
        $this.closest('p').css('font-size', fontSize);
      }
    }
  });

console.log(document.body.innerHTML);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">
        <b>The value conclusion of the Income Approach</b>
      </font>
    </font>
  </font>
</p>


<p class="western" style="margin-bottom: 0.14in">
  <font color="#000000">
    <font face="Arial, serif">
      <font size="1" style="font-size: 8pt">The client has specifically....</font>
    </font>
  </font>
</p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...