demaier demaier - 7 months ago 15
Javascript Question

How can I detect if the first nodeType inside a <li> is a nodeType 1 followed by nodeType 3?

I'm trying to find a way to detect if a hyperlink is the first node of a

<li>
.

For instance if I have:

<ul>
<li><a href="file.pdf">hyperlink</a> Text text text text...</li>
<li>Text text text text <a href="file.pdf">hyperlink</a>...</li>
</ul>


I need to find a way to detect that the first element/node inside the
<li>
is the link to the PDF. If the hyperlink is after the nodeType 3 (text) it should not pass the verification.

Given that, what I'm trying to accomplish is to assign a class to the
<li>
that stats with a hyperlink by using:

.closest('li').addClass('myclass');


So far what I got is:

$('li').contents().filter(function() {
return this.nodeType === 1;
}).closest('li').addClass('myclass');


Which doesn't do what I want.

How can I accomplish this?

Answer

Right now, you're filtering the contents on whether any of the nodes have a nodeType of 1, which would collect both lis. It sounds like you want to find if the first node is a link, which you'll need to find for each li.

    $('li').filter(function(idx, li) {
      return $(li).contents().first().is('a');
    }).addClass('myclass');
.myclass {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li><a href="file.pdf">hyperlink</a> Text text text text...</li>
  <li>Text text text text <a href="file.pdf">hyperlink</a>...</li>
</ul>

Comments