Getting the next element in a div with jquery - javascript

Say that we have this html code
<div id="test">
<h2>Title</h2>
<p>lorem ipsum</p>
</div>
And this jQuery
$("#test h2").text("Changed Title");
Now what is the correct way to continue down to the <p> and also change it's text, without going up one level.
Like next() will only look for the next h2, but is there something that gets the sibling independent of element type. Something like next("p"); maybe?

next chooses the next element: by default it does not only select an element of the same type.
$('#test h2').next(); // selects the p
$('#test h2').next('p'); // selects the p
$('#test h2').next('h2'); // does not select the p
Unless you provide a selector, next will choose the next sibling element. You can therefore do this:
$('#test h2').text('Changed title').next().text('Changed text');

The command your looking for is siblings("p")
Here is your example, updated:
$("#test h2").text("Changed Title").siblings('p').text('test');

.next( 'p' ) will do the trick:
$("#test h2").text("Changed Title")
.next( 'p' )
.text( 'Another change' );
From the jQuery docu:
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
See example fiddle here.

.next('p') will indeed work. Just chain it at the end. like this:
$('#test h2').text("Changed Title").next('p').text('I changed too');

$("#test h2").text("Changed Title").siblings().text("");

Just like you suggested,
$("#test").next("p").text('yada');
or even better:
$("#test h2").text("Changed Title").next("p").text('yada');

Exactly, you can do it by using the .next('p') method:
$("#test h2").next('p').text("...");

Related

Jquery select previous element with class

I have 3 elements:
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
on click on target div I test .prev() function in my js
$(document).on('click','.target',function(){
console.log($(this).prev().html());
console.log($(this).prev('.first').html());
});
Output is like: 'Second undefined', but should be like: 'second first' if I understand right the parameter of .prev() usage.
How can I get first previous element with certain class then?
Here is fiddle for you: http://jsfiddle.net/0fzgzce5/
From jQuery docs,
.prev()
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
To select all preceding sibling elements, rather than just the
preceding adjacent sibling, use the .prevAll() method.
http://api.jquery.com/prevAll/
So you should use console.log($(this).prevAll('.first').html());
You can make use of sibling() which will return the element with specific class and at same level as calling elment. But make sure that there is no same div after target
$(document).on('click','.target',function(){
console.log($(this).siblings('.second').html());
console.log($(this).siblings('.first').html());
});
DEMO
OR you can use prevAll()
$(document).on('click','.target',function(){
console.log($(this).prevAll('.second').html());
console.log($(this).prevAll('.first').html());
});
DEMO
Use prevAll() instead of prev()
$(document).on('click', '.target', function() {
alert($(this).prevAll('.second').html());
alert($(this).prevAll('.first').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
You can use also $("div:eq(3)") to get the exact element. Best example is $("ul li:eq(3)")
In your second console.log(), yous this is still .target and it does not have .first class so it is saying undefined.
To get the first dive, do:
console.log($(this).prev().prev().html());
Jquery .prev() always get immediate preceding sibling.
if you pass a selector as parameter it will filter the preceding element to match with, if it did not match it will return undefined, in your case this is happening
$('.target').prev().html()
is same as
$('.target').prev('.second').html();
which will return "Second"
If you pass any selector other than '.second' it alway return undefined so, your case
$('.target').prev('.first').html();
is as exprected, returning undefined because '.first' is not matching with preceding element selector.
Update:
if you want to get First the use
$('.target').prev().prev().html();

Replace the first header text with jquery

I have headers like
<h3 class="left_header">First job partner</h3>
<h3 class="left_header" style="text-align:center;">Don't have an account ?</h3>
Now i want to replace the first header with Job partner. how to do it by jQuery or Java script.
Try to grab the h3 tags with the class .left_header and take the first instance from the element collection using :first selector,
$('h3.left_header:first').text('Job partner')
DEMO
Try this:
$('h3:first-child').html('sublink_active');
Working Demo
Try this
$("h3:first-child").html("Job Partner")
demo
try with this.
$(".left_header:first").html("yourNewTitle");
JQuery :
$('.left_header').first().text("Job Partner");
you can use.first() (http://api.jquery.com/first/)
$( "h3" ).first().html("Job partner");
OR
you can use jQuery( ":first" ) (https://api.jquery.com/first-selector/)
$(".left_header:first").html("Job partner");
fiddle
Your code :
jQuery(".left_header h3").text("Public offers");
your code didn't match with your requirement. Because above code select all h3 elements under the "left_header" class. And In your HTML h3 have an class left_header. So you should use following selector to select elements-
$("h3.left_header");
Now you want to select only first element, so you can use index number like this -
document.getElementsByClassName("left_header")[0].innerText = "Job Partner";
OR
var g = $("h3.left_header");
$(g[0]).text("Job Partner");
Demo1
Demo 2
Note: There are more than one way exist to accomplish this task-
$(".left_header:first").text("Job Partner");
Working demo 1

How to loop and set the value of 2nd Span in Javascript?

I have a query in which i want to set the value of second span in the div.
<div id="content">
<h1>Welcome</h1>
<span>This is the first span</span>
<span>This is the second span</span>
<span>This is the 3rd span</span>
</div>
I am using following javascript.
function SetValue(myValue) {
var mainDiv = document.getElementById("content");
for(var i=0;i<mainDiv.childNodes.length;i++) {
if(mainDiv.childNodes[i] == 2) {
mainDiv.childNodes[i].innerText = myValue;
}
}
}
i want to get the parameter value to be set in second span of the main div
Inside SetValue, use this one line:
$("#content span:eq(1)").html(myValue);
Don't need the loop or any of that other stuff.
Docs on :eq
Fiddle of this working: http://jsfiddle.net/gromer/dB5vS/3/
simply use .eq() function
$('#content').find('span').eq(1).text("Your Value");
.eq function starts from index 0;
Here is the DEMO http://jsfiddle.net/Simplybj/n9HLU/2/
How about this pure JS implementation, since there is no indication, besides the tag, that JQuery is an option and it is totally not needed for something like this:
function SetValue(myValue){
document.getElementById("content").getElementsByTagName("span")[1].innerText = myValue;
}
http://jsfiddle.net/MTSAN/1/
Your if statement will have to check mainDiv.childNodes[i].tagName == "span" and increment a counter, setting the innerText once it has found the second . Alternatively (and better, in my opinion) several jQuery suggestions using nth-child css selectors have been posted.
This might help:
$(function() {
$('#content span:nth-child(2)').text('your text');
});​

jquery remove removing from another element

According to here, jquery's remove function should work like so..
$('div').remove('selector');
Which I'm trying in this example.
HTML:
<div class="wrapper">
<p class="unwanted">This should be removed</p>
<p class="retained">This will remain</p>
</div>​
JavaScript:
jQuery(document).ready(function($) {
$('div').remove('p.unwanted'); //not working
//$('p.unwanted').remove(); //this works
});
​
It's not working. What am I doing wrong?
You've misunderstood what the documentation is saying. It's not looking for elements that are descendants of the matched elements that match the selector, it's simply filtering down the set of already matched elements to those that match the selector, and then removing them.
If you have this HTML:
<div class="wanted">Some text</div>
<div class="wanted">Some more text</div>
<div class="unwanted">Some unwanted text</div>
and then executed this jQuery:
$('div').remove('.unwanted');
then it would only remove that third <div> (the one with the unwanted class on it), because it first selects all <div> elements, and then only removes those that match the selector.
Example jsFiddle
You're trying to remove something that is both div and p.unwanted. The filter in remove() is applied to the current set of nodes, which in this case is all div elements.
Use the children set instead:
$('div').children().remove('p.unwanted');
You should use the following:
$('p').remove('.unwanted');
Argument in remove works as a filter. So here, you first select all <p> elements and then remove only those which have class unwanted.
DEMO: http://jsfiddle.net/qwXSw/1/
try this
$(document).ready(function() {
$('div').find('p.unwanted').attr('class', '');
});

jquery .next isn't working?

take this simple code:
<div id="container">
<div class="box">abc</div>
<div class="box" id="secondbox">abc</div>
<div>generic</div>
<div>generic</div>
</div>
Now I add the class box to let's say the last div generic:
$('#container div:last').addClass('box');
Now if i try to select the next .box with this it doesnt' work:
$('#secondbox').next('.box')
returns .length=0
I presume what you actually mean is #container div:last.
next does not find the next element that matches a selector. It finds the next sibling element. If you supply a selector, it tests the element against that selector. If the test fails, an empty selection (i.e. length == 0) is returned.
You need nextAll:
$('#secondbox').nextAll('.box').first();
You should replace $('#container p:last').addClass('box'); with $('#container div:last').addClass('box');
And as lonesomeday said. You should use nextAll selector.

Categories