Home > database >  How to get inner html text of sibling element
How to get inner html text of sibling element

Time:09-16

Why doesn't this print out the text of the span, "Apple "?

<label class="search-recipe-chkbox fruitLabel">
  <input type="checkbox" class="checkbox check-box-mob-filters check-box-desktop" id="12DSKT" name="Apple" value="12">
  <span class="checkmark"></span>
  <span class="ingredient-label">Apple <span class="recipe-count" id="12numDSKT">(1)</span></span>
</label>
for (var checkbox of checkboxes) {
  if (checkbox.checked == true) {
    console.log($(checkbox.id).siblings('.ingredient-label').text());
  }
}

checkboxes is just all the checkboxes (input) in the form and given that Apple is checked.

Thank you

CodePudding user response:

There are multiple reasons that this could occur, however here is my solution to your problem.

for (var checkbox of checkboxes) {
  if (checkbox.checked) {
    var val = checkbox.parentElement.querySelector('.ingredient-label').textContent;
    console.log(val);       
  }
}   

CodePudding user response:

Check the checkbox.id - in the console.log

It needs to have a # in the front:

for (var checkbox of checkboxes) {
  if (checkbox.checked == true) {
    console.log($('#' checkbox.id).siblings('.ingredient-label').text()); // like this
  }
}

Edit

Here's a better solution as told by Teemu. Only checkbox also works:

for (var checkbox of checkboxes) {
  if (checkbox.checked == true) {
    console.log($(checkbox).siblings('.ingredient-label').text()); // like this
  }
}

CodePudding user response:

You can also use - console.log($("[id]").siblings('.ingredient-label').text());

  • Related