JQuery get all elements by class name - javascript

in the process of learning javscript and jquery, went through pages of google but can't seem to get this working. Basically I'm trying to collect innerhtml of classes, jquery seems to be suggested than plain javascript, into a document.write.
Here's the code so far;
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<script>
var mvar = $('.mbox').html();
document.write(mvar);
</script>
With this, only the first class shows under document.write. How can I show it all together like Block OneBlock TwoBlock Three? My ultimate goal with this is to show them comma seperated like Block One, Block Two, Block Three, Block Four. Thanks, bunch of relevant questions come up but none seem to be this simple.

One possible way is to use .map() method:
var all = $(".mbox").map(function() {
return this.innerHTML;
}).get();
console.log(all.join());
DEMO: http://jsfiddle.net/Y4bHh/
N.B. Please don't use document.write. For testing purposes console.log is the best way to go.

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:
var mvar = "";
$(".mbox").each(function() {
console.log($(this).html());
mvar += $(this).html();
});
console.log(mvar);

With the code in the question, you're only directly interacting with the first of the four entries returned by that selector.
Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/
I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq() is a little more explicit making this point than the answers using map, though map or each is what you'd probably use "in real life" (jquery docs for eq here).
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<body>
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<div id="outige"></div>
<script>
// using the $ prefix to use the "jQuery wrapped var" convention
var i, $mvar = $('.mbox');
// convenience method to display unprocessed html on the same page
function logit( string )
{
var text = document.createTextNode( string );
$('#outige').append(text);
$('#outige').append("<br>");
}
logit($mvar.length);
for (i=0; i<$mvar.length; i++) {
logit($mvar.eq(i).html());
}
</script>
</body>
</html>
Output from logit calls (after the initial four div's display):
4
Block One
Block Two
Block Three
Block Four

Alternative solution (you can replace createElement with a your own element)
var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

to get the input value you can do something like this:
var allvendorsList = $('.vendors').map(function () {
return this.value;
}).get();

Related

Search DOM for elements based on part of the class name [duplicate]

If I have the following:
<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>
I can use the following selector to find the first two DIVs:
$("div[class^='apple-']")
However, if I have this:
<div class="some-other-class apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>
It will only find the second DIV, since the first div's class is returned as a string (I think) and doesn't actually start with 'apple-' but rather 'some-'
One way around that is to not use starts with, but instead contains:
$("div[class*='apple-']")
The problem with that is it will also select the 3rd DIV in my example.
Question: Via jQuery, what is the proper way to use predicate selectors on individual class names, rather than the entire class attribute as a string? Is it just a matter of grabbing the CLASS, then splitting it into an array and then looping through each individual one with regex? Or is there a more elegant/less verbose solution?
Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.
While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:
You can use this custom jQuery selector, which I call :acp() for "A Class Prefix." Code is at the bottom of this post.
var test = $('div:acp("starting_text")');
This will select any and all <div> elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.
<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />
var startsWithapp = $('div:acp("app")');
This will return elements 1, 2, and 3, but not 4 or 5.
Here's the declaration for the :acp custom selector, which you can put anywhere:
$(function(){
$.expr[":"].acp = function(elem, index, m){
var regString = '\\b' + m[3];
var reg = new RegExp(regString, "g");
return elem.className.match(reg);
}
});
I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.
this is for prefix with
$("div[class^='apple-']")
this is for starts with so you dont need to have the '-' char in there
$("div[class|='apple']")
you can find a bunch of other cool variations of the jQuery selector here
https://api.jquery.com/category/selectors/
<div class="apple-monkey"></div>
<div class="apple-horse"></div>
<div class="cow-apple-brick"></div>
in this case as question Josh Stodola answer is correct
Classes that start with "apple-" plus classes that contain " apple-"
$("div[class^='apple-'],div[class*=' apple-']")
but if element have multiple classes like this
<div class="some-class apple-monkey"></div>
<div class="some-class apple-horse"></div>
<div class="some-class cow-apple-brick"></div>
then Josh Stodola's solution will do not work
for this have to do some thing like this
$('.some-parent-class div').filter(function () {
return this.className.match(/\bapple-/);// this is for start with
//return this.className.match(/apple-/g);// this is for contain selector
}).css("color","red");
may be it helps some one else thanks
Try this:
$("div[class]").filter(function() {
var classNames = this.className.split(/\s+/);
for (var i=0; i<classNames.length; ++i) {
if (classNames[i].substr(0, 6) === "apple-") {
return true;
}
}
return false;
})

how to get div content by role javascript

I'm trying to get feed content from facebook dom.
<div role="feed">
so i did that:
querySelectorAll($("div[role='feed']"))
like this:
get div by role
but it returns undifend result.
I tried some more similar way but still get undifend.
It is possible to get this data?
thanks
Please remove $. It's not needed and might throw an undefined error. Are you running after the page has loaded? Are you using .innerHTML to get the HTML contents? This works for me:
<div role="feed">Hello</div>
<script>
console.log(document.querySelector('div[role="feed"]').innerHTML);
</script>
In case, if you aren't running after your page has loaded, put your code inside onload event of window object.
You should change your code this way:
<script>
// Loading script before element.
window.onload = function () {
console.log(document.querySelector('div[role="feed"]').innerHTML);
}
</script>
<div role="feed">Hello</div>
This works if you are loading script before element.
You are mixing JavaScript and jQuery.
You don't need $() to do that with .querySelectorAll()
You don't need .querySelectorAll() to do that with $()
You can do any of the following to select the div with role="feed":
let divs_js = document.querySelectorAll("div[role='feed']");
console.log('Elements matched:', divs_js.length);
let divs_jq = $("div[role='feed']");
console.log('Elements matched:', divs_jq.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed"></div>
<div role="not-feed"></div>
<div role="feed"></div>
<div role="feed"></div>
<div role="not-feed"></div>
⋅
⋅
⋅
Here is an example of what you can do to get the content, then:
console.log("Using JS:");
let divs_js = document.querySelectorAll("div[role='feed']");
divs_js.forEach(function(elm){
console.log(elm.innerHTML); // or .innerText, according to your needs
});
// ----------------------
console.log("---------");
console.log("Using jQ:");
let divs_jq = $("div[role='feed']");
$(divs_jq).each(function(){
console.log($(this).html()); // or .text(), according to your needs
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed">feed 1</div>
<div role="not-feed">not feed 1</div>
<div role="feed">feed 2</div>
<div role="feed">feed 3</div>
<div role="not-feed">not feed 2</div>
Hope it helps.
With jQuery you don't need querySelectorAll() to get the DOM you can achieve this with $("div[role='feed']"). Since you are using querySelectorAll(), it accept string which must be a valid CSS selector string; if it's not, a SyntaxError exception is thrown. Since you are using wrong syntax, it returns undefined.
And you need text() function to get content of div in jQuery. text() get the combined text contents of each element in the set of matched elements, including their descendants, or set the text contents of the matched elements.
console.log($("div[role='feed']").text());
console.log($("div[role='feed']"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div role="feed">
so i did that:
</div>

Select a specific element from HTML data in a variable

I have stored the results of $.get() into a variable called questionsdata. The data is basically a bunch of divs with unique ids. I wish to find just one div using an id. I can kind of understand that this wouldn't work but I don't know what would.
$(questionsdata).find("#593");
Example data in the variable:
<div id="591">Stuff</div>
<div id="592">Stuff</div>
<div id="593">Stuff</div>
<div id="594">Stuff</div>
You can parse HTML stored in a text variable with jquery quite easily - it doesn't need to be added to the DOM.
As #593 is at the top level, .find will not find as it searches children. Instead you could use .filter if it will always be at the top level, or wrap in another <div> - either at the source or via jquery:
var data = '<div id="591">Stuff1</div><div id="592">Stuff2</div><div id="593">Stuff3</div><div id="594">Stuff4</div>';
console.log($(data).find("#593").length)
// Use .filter
console.log($(data).filter("#593").text())
// Or wrap with a div
console.log($("<div>").html(data).find("#593").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var questionsdata = '<div id="x"><div id="a591">Stuff1</div><div id="b592">Stuff2</div><div id="c593">Stuff3</div><div id="d594">Stuff4</div></div>'
console.log($('#b592',questionsdata ).html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your JavaScript
var data='<div id=591>Stuff</div>
<div id="592">Stuff</div>
<div id="593">Stuff</div>
<div id="594">Stuff</div>';
var $data = $(data).appendTo('#container");
var my_div=$("#container").find("#593");
Your HTML
< div id="container"></div>
Your CSS
#container{display:none;}

Each div must increments its counter upon clicking

I've three divs. Each div must increment its counter val upon clicking them.
HTML:
<body>
<content>
<div id="box1" class="v1" onclick="counter('box1')";>A : <span class="num">0</span></div>
<div id="box2" class="v2" onclick="counter('box2')">B: <span class="num">0</span></div>
<div id="box3" class="v3" onclick="counter('box3')">C: <span class="num">0</span></div>
</content>
</body>​
Javascript:
function counter(id){
var id = document.getElementById(id);
$('#id').click(function () {
update($("span"));
});
}
function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
​
Here is the code demo
You are doing a lot of work that jQuery would do for you. If you change your class to simply box and use the ID's to style your content, you can do the whole thing like this:
<body>
<content>
<div id="box1" class="box">A: <span class="num">0</span></div>
<div id="box2" class="box">B: <span class="num">0</span></div>
<div id="box3" class="box">C: <span class="num">0</span></div>
</content>
</body>
$( function() {
$('.box').click( function() {
var num = $(this).find('.num');
num.text( parseInt(num.text()) + 1 );
});
});
Example: http://jsfiddle.net/ddvQU/1/
Some thoughts:
If a style is unique to a single element (now and in the future), you should be using IDs. Styles that are (or will be) common to multiple elements should use classes.
Using inline javascript onclick='blah()' is more difficult to manage, as it is not as easy to debug, does not allow for code reuse, and forces you to make updates in lots of places when you change code. It also makes you do nasty things like escaping quotes.
var id = document.getElementById(id); <= The whole reason we have jQuery is so that we don't have to do this. Simply do $('#'+id). (ok, maybe not the whole reason, but one of them).
You don't need to do the above if you attach a jQuery handler to your class of elements (see the first bullet). The handler will already have a reference to the object, even if it doesn't even have an ID.
I would use .on() instead of .click(), but as you look to be new to jQuery, get this to work first, and then look into why on() is better, and how to do it.
Assign a click function to your div that does:
$('#div_id').html(parseInt($('#div_id').html())++)
or something along those lines.
http://jsfiddle.net/4eqve/32/
Use a closure to store a counter variable for each DIV.
Attach a click handler.
Change counter function to this:
function counter(id){
update( $('#'+id+">span") );
}
http://jsfiddle.net/4eqve/24/
demo stores each count in data. One big thing that would have helped you is apply a common class to the elements you want to bind handler too as you'll see in this demo with added class "box"
If you're using jQuery then you might as well use the click handler it provides. You were quite close with your implementation, but you need to make sure that you're referencing the correct elements. I changed it so that you are passing the box div to the update function, that then selects the correct span from inside that div element.
// jQuery onclick for the boxes
$('#box1, #box2, #box3').click(function() {
update(this);
});
function update(j) {
var span = $(j).children('span');
var n = parseInt(span.text())+1;
span.text(n);
}
Here's the jsFiddle: http://jsfiddle.net/4eqve/29/
​
Fixed that for you.
It is much cleaner when you have clean html, and seperate the javascript to do the work.
<body>
<content>
<div id="box1" class="count-div">A : <span class="num">0</span></div>
<div id="box2" class="count-div">B: <span class="num">0</span></div>
<div id="box3" class="count-div">C: <span class="num">0</span></div>
</content>
</body>​
$(function(){
$(".count-div").click(function(){
amount = 1;
value = parseInt($(this).find("span").html());
$(this).find("span").html(value+amount);
});
});
You can even clean that up more so you have less code. If you have any question ask me
http://jsfiddle.net/4eqve/33/
There are many bugs in your script. Not to mentione, the markup selection is quite vague.
With a little update to some mark-ups, we can do this with a tiny snippet.
$(".clicable").click(function() {
$(this).children("span").html(parseInt($(this).children("span").html()) + 1);
});
Check the demo here

how to remove tags with JavaScript regular expressions

I have a JavaScript string containing HTML like this:
<div>
<div class="a">
content1
</div>
content 2
<div class="a">
<b>content 3</b>
</div>
</div>
and I want to remove the div's of class="a" but leave their content.
In Python I would use something like:
re.compile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)
What is the equivalent using Javascript regular expressions?
Why don't you use proper DOM methods? With a little help from jQuery, that's dead simple:
var contents = $('<div><div class="a">content1</div>content 2<div class="a"><b>content 3</b></div></div>');
contents.find('.a').each(function() {
$(this).replaceWith($(this).html());
});
You can achieve it with regular expressions in JavaScript
var html = '<div> <div class="a"> content1 </div> <div class="a"> content1 </div> ... </div>';
var result = html.replace(/<div class="a">(.*?)<\/div>/g, function(a,s){return s;});
alert(result);
RegExp method replace takes two parameters - first one is the actual re and the second one is the replacement. Since there is not one but unknown number of replacements then a function can be used.
If you want to do this in Javascript, I'm presuming that you are running it in a web browser, and that the 'javascript string' that you refer to was extracted from the DOM in some way.
If both of these case are true, then I'd say that it would be a good idea to use a tried and tested javascript library, such as JQuery (There are others out there, but I don't use them, so can't really comment)
JQuery allows you to do on-the-fly DOM manipulations like you describe, with relative ease...
$('div.a').each(function(){$(this).replaceWith($(this).html());});
JQuery is definitely one of those tools that pays dividends - a failry short learning curve and a whole lot of power.

Categories