I want to get leaf elements containing specific text, and I used :contains selector. However, this selector selects includes every parent nodes too. Here is my example.
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>
In this case, I just want to get elements containing text balloon. I expected to get 3 elements(target1, target2, target3) by $(":contains('balloon')"), but it returns every nodes including parent nodes of targets. (e.g. html, body, and every parent div)
How can I select only targets?
p.s Above HTML is only example. HTML can be vary, so the answer should be generic.
use indexOf("balloon") > -1 to find id the word balloon is found
var arr = $("div").children().map(function(){
if($(this).text().indexOf("balloon") > -1 )
return $(this).attr("id")
}).get();
console.log(arr)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>
The solution below, look for all elements containing the word and clone these elements, This way we can be sure only to get "correct" amount of elements
Just remove .length and you have access to the elements.
var s = $(":contains('balloon')").not("script").filter(function() {
return (
$(this).clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.filter(":contains('balloon')").length > 0)
}).length;
console.log(s)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<p id='target1'>Red balloon</p>
<div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
<span id='target3'>Brown balloon</span>
</div>
Related
<div>
<div id="div2">TEXT</div>
</div>
<div>
<div id="div2">TEXT</div> <!-- select this -->
</div>
<div id="div1">TEXT</div>
How to select div2 that is closest to div1
Following w3 docs
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.
So make sure your elements id are unique. Can switch to class instead
To select element closet to target element can use Element.closest()
The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null
<div id="div-01">Here is div-01
<div id="div-02">Here is div-02
<div id="div-03">Here is div-03</div>
</div>
</div>
var el = document.getElementById('div-03');
var r1 = el.closest("#div-02");
// returns the element with the id=div-02
I want to know how to access a specific element in a div when foreach-ing
Here is some code
HTML
<div class="row menu-filter-items">
<div class="col-md-4 margin-b-30 menu-item">
<a href="#" class="menu-grid">
<img src="images/img-1.jpg" alt="" class="img-fluid"/>
<div class="menu-grid-desc">
<!-- <span class="price float-right">$9.50</span> -->
<h4 class="a" id="title">Restaurant y</h4>
<p>
Description
</p>
</div>
</a>
</div>
</div>
Jquery:
$('#search').keyup(function(e){
var current_query = $('#search').val();
if(current_query != null)
{
$("div.menu-filter-items").hide();
$("div.menu-filter-items div.menu-item").each(function(){
var current_keyword = $(this).children('#title').text();
alert(current_keyword);
if (current_keyword.indexOf(current_query) >=0)
{
$("div.menu-filter-items").show();
}
});
}
else
{
$("div.menu-filter-items").show();
}
});
I want to access the H4 balise but I couldn't
Help please
thank you
Use
var current_keyword = $(this).find('#title').text();
instead of
var current_keyword = $(this).children('#title').text();
You should use find method.
The .children() method allows us to search through the children of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements as well.
You can use find to perform a search with Jquery lib.
See full doc here : https://api.jquery.com/find/
For your case; you can use :
$( "div.menu-filter-items" ).find( "h4" )
I have list of posts in Wordpress its looks like this:
<div class="products uk-grid uk-grid-width-medium-1-4">
<h3>AShape(14)</h3>
<h3>AShape(20)</h3>
<h3>CShape(38)</h3>
<h3>FShape(1)</h3>
<h3>FShape(4)</h3>
<h3>ZShape(2)</h3>
<h3>ZShape(24)</h3>
</div>
I need to find some way to pass all links through script and transform it in letter groups. So it should take first letter from all <h3> of links and make groups like this:
<div class="products uk-grid uk-grid-width-medium-1-4">
<div>
<span>A</span>
<h3>AShape(14)</h3>
<h3>AShape(20)</h3>
</div>
<div>
<span>C</span>
<h3>CShape(38)</h3>
</div>
<div>
<span>F</span>
<h3>FShape(1)</h3>
<h3>FShape(4)</h3>
</div>
<div>
<span>Z</span>
<h3>ZShape(2)</h3>
<h3>ZShape(24)</h3>
</div>
</div>
How i can do it using jQuery?
here i have simple codepen: http://codepen.io/ponciusz/pen/EPgQKP
You could iterate over each of the children elements and create corresponding containers for each letter. In the example below, a div container is appending with a custom data-letter attribute if a container does not already exist for that letter.
As I mentioned in the comments, I'd also suggest placing the a element inside of the h3 elements as well:
$('.products > h3').each(function () {
var letter = $('a', this).text().charAt(0);
if (!$(this).parent().find('[data-letter="'+ letter +'"]').length) {
$(this).parent().append('<div data-letter="'+ letter+'"><span>'+ letter +'</span></div>');
}
$(this).parent().find('[data-letter="'+ letter +'"]').append(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="products uk-grid uk-grid-width-medium-1-4">
<h3>AShape(14)</h3>
<h3>AShape(20)</h3>
<h3>CShape(38)</h3>
<h3>FShape(1)</h3>
<h3>FShape(4)</h3>
<h3>ZShape(2)</h3>
<h3>ZShape(24)</h3>
</div>
I wanna be able to select a specific set of child in which an attribute is defined.
But how to select childs which are first child of the root selector that having the attribute data-role
first-of-type selector doesn't work due to the type of the element.
Here we have a sample of the DOM.
<body>
<div data-role="ca:panel" title="foo">
<div data-role="ca:vbox" width="100%">
<div data-role="ca:form">
<div data-role="ca:formitem">
<div data-role="ca:hbox">
<input data-role="ca:textinput">
<div data-role="ca:menu"></div>
</div>
</div>
<div data-role="ca:formitem">
<input data-role="ca:passwordinput">
</div>
<div data-role="ca:formitem">
<select data-role="ca:combobox">
<option>[...]</option>
</select>
</div>
</div>
<table>
<tbody>
<tr>
<td>
<span data-role="ca:label"></span>
</td>
<td>
<button data-role="ca:button"></button>
</td>
<td>
<button data-role="ca:button"></button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
My filter should select only
<div data-role="ca:form">
<span data-role="ca:label"></span>
<button data-role="ca:button"></button>
<button data-role="ca:button"></button>
It should work in any case, meanings, it shouldn't be linked to a specific structure of the dom and must use data-role as 'selector'.
I'm not a relevant jQuery developer. I tried some selector such as $('[data-role]:first-of-type'); but it doesn't work.
Do you have an idea to select the right set of child.
Note: Finding the first parent is not a concern.
It is possible to do this generically using a filter, so long as you have a start node:
JSFilter: http://jsfiddle.net/TrueBlueAussie/2uppww9s/5/
var root = $('[data-role="ca:vbox"]');
var matches = root.find('[data-role]').filter(function(){
return $(this).parentsUntil(root, '[data-role]').length == 0;
});
alert(matches.length);
You can use the :first pseudonym to select the first occurance of a element like for example:
var elm = $('*[data-role="ca:form"]:first');
this will select * any type of DOM-element, with the data-role that matches "ca:form"
Since you want to return two buttons with the same data-role, we cant use ":first" for that. You would have to get the first child of a that matches in that case
var elm = $('td').children('button[data-role="ca:button"]:first');
This will look through the child elements of all TD-tags and find the first button with data-role matching "ca:button"
If you want first of all overall specifications, then you can simply use selector on all three tag types and filter them as so:
$('div, span, button').filter(function(i){
if (this.tagName == 'DIV' && $(this).data('role') == 'ca:form') return true;
if (this.tagName == 'SPAN' && $(this).data('role') == 'ca:label') return true;
if (this.tagName == 'BUTTON' && $(this).data('role') == 'ca:button') return true;
}).first();
Using .first grabs the first of them.
Also, filter can be used in a million ways to get what you want and sounds like it may get you to what you need. Just set what you're filtering for in an if/for/switch statement and return true on items that match.
jsFiddle
However, if you wanted first of each you could do something like:
$('div[data-role="ca:form"]:first, span[data-role="ca:label"]:first, button[data-role="ca:button"]:first')
If variable driven in someway, just use string concatenation.
jsFiddle
Say I have 3 elements like below with different html contents:
<div id='result1'> <p>One</p> </div>
<div id='result2'> <p>Two</p> </div>
<div id='result3'> <p>Three</p> </div>
How can I copy just contents within the div element to the next one so that the final result looks like this?
<div id='result1'> <p>New content</p> </div>
<div id='result2'> <p>One</p> </div>
<div id='result3'> <p>Two</p> </div>
There will be new content for replacement and the last content can be discarded.
To clarify, I'll have something like:
<div id='new'> <p>New content</p> </div>
where I want to grab '<p>New content</p>' as new content to use.
What do you think?
To push the content down, reverse the collection and set the HTML to the HTML of the previous one.
var elems = $($('[id^=result]').get().reverse());
elems.html(function(i) {
return elems.eq(i+1).html();
}).last().html('New Content');
FIDDLE
You can use .html() on the element you want to change the content. For accessing particular element you can use ID Selector (“#id”) with Child Selector (“parent > child”).
Live Demo
$('#result1 > p').html('New content');
Edit to move contents to next elements you can iterate through all elements and start assigning the context of second last to last, third last to second last and so on
Live Demo
elements = $('[id^=result] > p');
len = elements.length;
elements.each(function(idx, el){
if(idx == elements.length-1) return;
$('#result'+ (len-idx) + ' p').html($('#result' + (len-idx-1) + ' p').html());
});
$('#result1 > p').html('New content');
try JS fiddle
I am suggesting to add a Parent Grid and use jquery first() and last(), These controls will function like a queue.
$('#Pdiv').children().last().remove();
$('#Pdiv').first().prepend("<div id='new'> <p>I am New One</p></div>");
alert($('#Pdiv').children().first().html());