How to get html from element by id with jQuery - javascript

I have simple list:
<ul id="tabs_nav">
<li id="t_00">data</li>
<li id="t_01">data</li>
<li id="t_02">data</li>
<li id="t_03">data</li>
</ul>
Now: How do I get the html of the first element, depending on what is ID. I would add that all of ID's change dynamically with the click of the button. This is my code:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
Thx for help.

Seems you are missing the id selector #.
You are trying to get the html from the selector:
ladder_nav_tabs.find(first_ladder_element_inset_id).html();
This won't work as an id selector needs the #. Like this:
ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
Try the following to fix your code:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
DEMO - Updating to valid id selector syntax
Alternatively you could shorten your code using jQuery's eq, similar to this:
btn.on('click',function(){
var theHtml = $('#tabs_nav li').eq(0).html();
console.log(theHTML);
});

Don't use jQuery purely as a selector engine:
btn.onclick = function() {
console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};

Check out the jQuery first-child selector. Specifically:
btn.on('click',function(){
var first_child = $('#tabs_nav li:first-child');
var first_child_html = first_child.html();
});

Try this:
btn.on('click',function(){
var ladder_nav_tabs = $('#tabs_nav'),
first_ladder_element_inset_id = ladder_nav_tabs.find('li:first-child').attr('id'),
first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
console.log(first_ladder_element_inset_html);
});
You have tou use :first-child

Related

Replace the text using javascript

Im using the below code to replace the text within the h1 tag, but its not getting effected. I want to replace "sample" to "new sample". I'm doing wrong?
<div class="content">
<h2>sample</h2>
</div>
var t = jQuery('.content');
t.children("h2").each(function() {
var contents = jQuery(this).contents();
jQuery(this).replaceWith(new sample);
});
use .html() to set html.try this:
$('.content h2').html('new sample');
Working Demo
If you want to replace some part of content then try this:
jQuery('.content h2').each(function(i, v) {
$v = $(v);
$v.html($v.html().replace('sample', 'new sample'));
});
jsFiddle
Use jQuery's .text()
$(".content h2").text("new sample");
FIDDLE
You can do that without jQuery:
var elem = document.getElementsByTagName('h2')[0];
elem.innerHTML = "New Value";
Set .text()
t.children("h2").text('new sample'));
If you want to set .html() content
t.children("h2").html('new sample'));
Child Selector (“parent > child”)
$('.content > h2').html('new sample');

remove extra space after adding text with jquery

My html markup is looking like this : <div id="somediv"> [whitespace] text</div> and I'm adding this value like inside an input element like this:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text());
jQuery('input[name="search"]').keyup();
});
This works fine but the problem is that is adding the value with the whitespaces and I don't want this.
I've found this jquery method jQuery.trim() which seems to remove all the whitespaces but I don't know how can I use it inside my actual function.
Can someone give me some suggestions on how achieve this ?
Chain the method to the text
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
Use trim(). Like:
jQuery('.votefilters span a:first').on('click', function(event) {
jQuery('input[name="search"]').val(jQuery('.myo-poll-bar.firstoption').text().trim());
jQuery('input[name="search"]').keyup();
});
I recommend you "cache" your jQuery calls, so I did it by using oSearch. (Line 1)
then to answer your jQuery.trim question... do it like this
var oSearch = jQuery('input[name="search"]');
jQuery('.votefilters span a:first').on('click', function(event) {
var text = jQuery('.myo-poll-bar.firstoption').text();
text = jQuery.trim( text );
oSearch.val( text );
oSearch.keyup();
});
jQuery.trim('yourtext') similar to this:
jQuery('.votefilters span a:first').on('click', function (event) {
var $input = jQuery('input[name="search"]');
var newText = jQuery('.myo-poll-bar.firstoption').text();
var trimmedText = jQuery.trim(newText);
$input.val(trimmedText);
$input.keyup();
});
DEMO - Using jQuery.trim();

Get DIV ID where Class is selected?

I currently have the following:
$(window).load(function(){
$(".boxdiv").click(function () {
$(this).toggleClass("selected");
});
});
Which perfectly does the first part of what I need. I have a fair amount of div's with the class "boxdiv" and they each have a unique ID that will identify it. What I need to happen is to have some kind of button that when pressed sends all of these div ID's with the class selected, to the next page.
Anyone got any idea of how I can do this?
Map the ID's in an array, and use $.param to create a querystring
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;});
window.location.href = '/next_page?' + $.param({ids : id_arr});
});
EDIT:
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
window.location.href = '/next_page?ids=' + qs;
});
Perhaps this is what you're looking for:
$(".button").click(function(){
var id_arr = [];
$(".boxdiv").each(function(){ // Loop through each element with that class
id_arr.push($(this).attr('id'));
}); // Loop through each element with that class
});
window.location = 'next.html/ID=' + id_arr.join(',');
The ID's should be stored in id_arr
You can loop over each div that has the class selected. You can then use attr() to access the ID names.
Javascript
var ids = [];
$.each($(".selected"), function() {
ids.push($(this).attr('id'));
});
ids = ids.join(',');
HTML
<div id="boxA"></div>
<div id="boxB" class="selected"></div>
<div id="boxC" class="selected"></div>
<div id="boxD"></div>
This should return ["boxB", "boxC"]
See: http://jsfiddle.net/B4V28/1/
All of the answers submitted are in fact correct - but I think the real issue is your expectation of what jQuery is doing for you.
jQuery will gather all of the ID's in any manner, but you will need to have a way to collect them on the next page and actually do something with them. This will all need to happen server side.
Most likely, the ideal method, based on your comment of "potentially there could be many" you would want to do a mapping (see other answers), and pass the json object to your server, where it can pass it to the next page.
With the same code -
$('button').on('click', function() {
var id_arr = $.map($(".selected"), function(el) {return el.id;}),
qs = encodeURIComponent(id_arr.join(','));
alert('/next_page?ids=' + qs);
});
Here is a fiddle for you - http://jsfiddle.net/kellyjandrews/4dYfh/

how to get content of all <li> tags in one page using jquery

I have an html list something like this:
<li id="tag">red</li>
<li id="tag">yellow</li>
<li id="tag">blue</li>
How can I get the content of these li tags using jQuery?
For example;
$tags = red, yellow, blue
You can use jQuery.map()
Live Demo
texts = $('li').map(function(){
return $(this).text();
}).get().join(',');
var $tags = $("li").map(function(){
return $(this).text();
}).get().join(",");
Here, have a fiddle: http://jsfiddle.net/KTted/2/
First, you should change your id="tag" to class="tag", as you can't have multiple elements with the same id.
You can build an array of the values:
var content = [];
$("li").each(function (element) {
content.push[$(element).text()];
});
Or as others have pointed out, you can use map:
var content = $("li").map(function() {
return $(this).text();
}).get().join(",");

jquery get certain class name of element which has several classes assigned

I need to read elements class name. I have elements like this:
<article class="active clrone moreclass">Article x</article>
<article class="active clrtwo moreclass">Article y</article>
<article class="active clrthree moreclass moreclass">Article z</article>
<article class="active clrone moreclass">Article xyza</article>
I need to parse out class name that starts with clr. So if second element was clicked then I would need to get clrtwo className.
You can use a regular expression match on the class name of the clicked item to find the class that begins with "clr" like this:
$("article").click(function() {
var matches = this.className.match(/\bclr[^\s]+\b/);
if (matches) {
// matches[0] is clrone or clrtwo, etc...
}
});
Here is solution for you:
$('article').click(function () {
var className = this.className.split(' ');
for (var i = 0; i < className.length; i+=1) {
if (className[i].indexOf('clr') >= 0) {
alert(className[i]);
}
}
});
http://jsfiddle.net/vJfT7/
There's no matter how you're going to order the different classes. The code will alert you a class name only of there's 'clr' as a substring in it.
Best regards.
If you don't need to find elements based on these classes (e.g. doing $('.clrtwo')) it would be nicer to store the data as a data-clr attribute. This is standards-compliant from HTML5, and is supported by jQuery using the .data() function.
In this instance, I would modify your HTML in this way:
<article class="active moreclass" data-clr="one">Article x</article>
<article class="active moreclass" data-clr="two">Article y</article>
<article class="active moreclass moreclass" data-clr="three">Article z</article>
<article class="active moreclass" data-clr="one">Article xyza</article>
I would then use Javascript like this:
$('article.active').click(function() {
console.log($(this).data('clr'));
});
jsFiddle example
If it is always the second class name which is of interest you can do this:
$("article").click(function () {
// split on the space and output the second element
// in the resulting array
console.log($(this)[0].className.split(" ")[1]);
});
http://jsfiddle.net/karim79/Z3qhW/
<script type="text/javascript">
jQuery(document).ready(function(){
$("article").click(function(){
alert($(this).attr('class').match(/\bclr[^\s]+\b/)[0]);
});
});
</script>
This should jquery script should do what you asked (tested on jsfiddle):
$(document).ready(function () {
function getClrClass(elem) {
var classes = elem.getAttribute('class').split(' ');
var i = 0;
var cssClass = '';
for (i = 0; i < classes.length; i += 1) {
if (classes[i].indexOf('clr') === 0) {
cssClass = classes[i];
i = classes.length; //exit for loop
}
}
return cssClass;
};
$('article').click(function (e) {
var cssClass = getClrClass($(this)[0]);
alert(cssClass);
e.preventDefault();
return false;
});
});
Hope this helps.
Pete
Use an attribute selector to get those that have class names that contain clr.
From there:
extract the class name (string functions)
analyze the position
determine the next element
The latter two might be best served by a translation array if you only had a few classes.
UPDATE
I agree with lonesomeday, you'd be far better off using data-* attribute to handle such logic. Using CSS as JavaScript hooks is a thing of the past.
http://jsfiddle.net/4KwWn/
$('article[class*=clr]').click(function() {
var token = $(this).attr('class'),
position = token.indexOf('clr');
token = token.substring(position, token.indexOf(' ', position));
alert(token);
});

Categories