How to loop and set the value of 2nd Span in Javascript? - 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');
});​

Related

How to get element by both id and class

Is there any alternative solution (in JavaScript) for document.getElementById(); to select a specific element, specifying both the class and id ?
for example I have such a content:
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="2"></div>
And I want to select the corresponding div under the "Question X" link in the function
function showQuestion(id)
{
var thediv = GetByClassAndId("q_content",id); // how to implement this function ?
WriteQuestionIn(thediv); //Ajax
}
Thanks in advance.
you can try document.querySelector()
like document.querySelector(".q_content#2") use the para like css selector..
Since ID is always unique (unless u make a mistake) u have no need to use both class and id to select the element.
Such an approach is not correct, and should be avoided at all cost.
What I suspect is your problem, is that the ID is only a number. Try adding a prefix which is a letter. Do view source to this page to see examples.
<a class="q_href" onclick="showQuestion(1)">Question 1:</a>
<div class="q_content" id="q1"></div>
<a class="q_href" onclick="showQuestion(2)">Question 2:</a>
<div class="q_content" id="q2"></div>
function showQuestion(id)
{
var thediv = document.getElementById("q"+id);
WriteQuestionIn(thediv); //Ajax
}
Actually there is a function $ in jQuery for doing this operation. If you are using any framework, then you should remember there is always a jQuery library available. Else if you are using custom PHP, then add one of them like jQuery or other because they provide lots of types of selectors.
Now here is the code after adding jQuery:
$("#yourid") //basic selector
$("#yourid.yourclass").show()
Use .show() to show the selected element
Use .hide() To hide element

Getting the next element in a div with jquery

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("...");

How to merge paragraphs into parent link with jquery / Javascript?

How do I turn this:
<a class="link">
<p class="paragraph">This is some text</p>
<p class="paragraph">This is some more text</p>
<p class="paragraph">And some more</p>
</a>
into this:
<a class="link">
This is some text This is some more text And some more
</a>
with jQuery. I tried using append and merge but I just can't figure it out.
Since the text method returns the text content of an element and it's descendants, you can just use that:
var link = $("a.link");
link.text(link.text());​​​​​​​​​
From the docs:
Get the combined text contents of each element in the set of matched
elements, including their descendants.
Here's a working example.
Update (see comments)
In the case that this needs to apply to multiple .link elements, you can use each:
$("a.link").each(function() {
$(this).text($(this).text());
});
This will work:
$("a.link").text(function(i,text){
return text;
});
And yet another way (not tested):
// you can optionally filter to
// only p elements too with
// .children("p")
$("a.link").children().contents().unwrap();
Here's another variation of the second:
$("a.link p").contents().unwrap();
Edit: Just a note for clarity:
All of these solutions work on multiple elements. The first solution is a relatively uncommon syntax that can be used on most jQuery setter functions. It runs the callback on each matched element and sets the value of the property/attribute to the value returned from the callback.
try this
$(document).ready(function(){
var concatText = "";
$("p.paragraph").each(function(){
concatText = concatText + " " + $(this).text()
});
$("a.link").html(concatText);
​ });​

How to select HTML elements which don't have any attributes defined on them?

I need to use jQuery to locate all DIV tags that have no attributes on them and apply a class to each. Here's a sample HTML:
<div id="sidebar">
<div>Some text goes here</div>
<div class="something">something goes here</div>
<div>Another div with no attributes.</div>
</div>
So, I need to take that and turn it into this:
<div id="sidebar">
<div class="myClass">Some text goes here</div>
<div class="something">something goes here</div>
<div class="myClass">Another div with no attributes.</div>
</div>
How do you locate elements of type div that have no attributes via jQuery? Thanks.
Here you go:
$('div', '#sidebar').filter(function () {
return this.attributes.length === 0;
})
Live demo: http://jsfiddle.net/phbU9/
The attributes property returns a list of all attributes set on the element. "Naked" elements have an empty attributes list.
Update: Be sure to read Tim's answer below which provides a solution for older versions of IE, since my own solution doesn't work in IE8 and below.
#Šime's answer is close but doesn't work in IE 6, 7 or 8, where an element's attributes collection has an entry for every possible attribute, not just those specified in the HTML. You can get round this by checking each attribute object's specified property.
Live demo: http://jsfiddle.net/timdown/6MqmK/1/
Code:
$("div").filter(function() {
var attrs = this.attributes, attrCount = attrs.length;
if (attrCount == 0) {
return true;
} else {
for (var i = 0; i < attrCount; ++i) {
if (attrs[i].specified) {
return false;
}
}
return true;
}
});
check this out:
http://jsfiddle.net/thilakar/CHux9/
You need to give some sort of selector, in this case Ive used your side bar but it can be anything. Then get the children that have no class attribute and add a new class. See JSFiddle for the example:
http://jsfiddle.net/HenryGarle/q3x5W/
$("#sidebar").children('div:not([class])').addClass('newClass');
So this would return the 2 elements with no class tag and leave the sidebar and div with the class completely unaffected.
You could use a combination of jQuery's has attribute selector and the not selector. For example:
$('div:not([class], [id])').addClass('myClass');
jsFiddle demonstrating this
With this approach, you need to explicitly specify the attributes to check the presence of. Sime's solution would apply the class to divs that do not have any attributes at all.
To expound upon Tim Down's answer, I recommend checking that the attrs var not null special cases where the html has comment tags, etc.
try $('div:not([class])').addClass('myClass');
it is a general approach because the class will apply to all the div that have no class
$('#sidebar div')` or more general `$('div'); //returns collections of divs
to answer the question:
$('#sidebar div').addClass('myClass');

How to clear all <div>s’ contents inside a parent <div>?

I have a div <div id="masterdiv"> which has several child <div>s.
Example:
<div id="masterdiv">
<div id="childdiv1" />
<div id="childdiv2" />
<div id="childdiv3" />
</div>
How to clear the contents of all child <div>s inside the master <div> using jQuery?
jQuery's empty() function does just that:
$('#masterdiv').empty();
clears the master div.
$('#masterdiv div').empty();
clears all the child divs, but leaves the master intact.
jQuery('#masterdiv div').html('');
Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.
$('#masterdiv div').empty();
Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.
I know this is a jQuery related question, but I believe someone might get here expecting a pure Javascript solution. So, if you were trying to do this using js, you could use the innerHTML property and set it to an empty string.
document.getElementById('masterdiv').innerHTML = '';
jQuery recommend you use ".empty()",".remove()",".detach()"
if you needed delete all element in element, use this code :
$('#target_id').empty();
if you needed delete all element, Use this code:
$('#target_id').remove();
i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED
ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/
If all the divs inside that masterdiv needs to be cleared, it this.
$('#masterdiv div').html('');
else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.
$('#masterdiv div').each(
function(element){
if(element.attr('id').substr(0, 8) == "childdiv")
{
element.html('');
}
}
);
The better way is :
$( ".masterdiv" ).empty();
$("#masterdiv div").text("");
$("#masterdiv > *").text("")
or
$("#masterdiv").children().text("")
$('#div_id').empty();
or
$('.div_class').empty();
Works Fine to remove contents inside a div
You can use .empty() function to clear all the child elements
$(document).ready(function () {
$("#button").click(function () {
//only the content inside of the element will be deleted
$("#masterdiv").empty();
});
});
To see the comparison between jquery .empty(), .hide(), .remove() and .detach() follow here http://www.voidtricks.com/jquery-empty-hide-remove-detach/
When you are appending data into div by id using any service or database, first try it empty, like this:
var json = jsonParse(data.d);
$('#divname').empty();
$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});
or
$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});
try them if it help.
$('.div_parent .div_child').empty();
$('#div_parent #div_child').empty();

Categories