简体   繁体   中英

How to get the text closest to the html element tag

I got this html snippet:

<label>
  <input type="checkbox"/>
  text here
</label>

in my js, i want to retrieve the 'text here' value

this is my js:

$('input[type=checkbox]').click(function (e) {
var msg = e.target.closest???
});

You can use DOM node nextSibling property:

$('input[type=checkbox]').click(function (e) {
    var msg = this.nextSibling.nodeValue;
    console.log(msg);
});

 $('input[type=checkbox]').click(function (e) { var msg = this.nextSibling.nodeValue; alert(msg); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <label> <input type="checkbox" />text here </label> 

You can use contents()

 $('input[type=checkbox]').click(function(e) { var contents = $(this).closest('label').contents(); var msg = contents[2]; console.log(msg); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <label> <input type="checkbox" />text here </label> 

Or in your simple case, text() and trim()

 $('input[type=checkbox]').click(function(e) { var msg = $(this).closest('label').text().trim(); console.log(msg); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <label> <input type="checkbox" />text here </label> 

parent() and text() combined seem a good way to get that text. Click run below and then click your label.

 $('input[type=checkbox]').click(function (e) { var msg = $(this).parent().text() $('#t').text(msg) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="checkbox"/> text here </label> <p id="t"></p> 

About the nextSibling solutions, if your text is before the <input> , there will be nothing to return... Since you have just a <label> as parent, in this particular case, I'd personally recommend using the <input> 's parent() and then its text() , which will always return all the text inside the <label> and nothing else: a checkbox does not have text(s) associated.

Try with nextSibling property of javascript.

Code snippets:

$('input[type=checkbox]').click(function (e) {
    var ele = $(this);
    var msg = ele[0].nextSibling.nodeValue;
    alert(msg);
    });

Hope this helps you!!!

You can use .closest() function of jQuery

$('input[type=checkbox]').click(function(e) {
  var msg = $(this).closest('label').text();
  alert(msg);
});

以下代码段适用于您的HTML

 $('input[type=checkbox]').parent().text(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM