Select a specific element from HTML data in a variable - javascript

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;}

Related

Insert Javascript variable value into HTML tag id field

I am trying to organize a bunch of id tags, I would like to be able to set up a single JavaScript variable which holds all manner of interesting information. One place I would like to use it, is to set the value of an id field in an HTML tag
<script>
var messageID = { idText: "message1", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="JavaScript.messageID.idText">Text One</div> <!-- abject failure -->
So basically I want the messageID.idText value to be the id value: id="message1". Obviously the example fails in the second div line. Is there a way to do this?
Edit:
Ok, I want to be able to use the value of messageID.idText elsewhere in the system, such as
var elementTag = document.getElementById(messageID.idText);
I use the id in many places, and the more there are, the better a chance of mis-typing something. This is not a small project :-)
So I am going with:
<?php
$msgOneId = "message1";
?>
<script>
var messageID = { idText: "<?=$msgOneId?>", other: "qwerty"};
</script>
<div id="message0">Text Zero</div>
<div id="<?=$msgOneId?>">Text One</div>
and then
var elementTag = document.getElementById(messageID.idText);
works

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>

creating multiple containers and modifying their divs

I have a popup, within the pop up is the following code, it contains a “container”, which forms a template:
<form method="post" class="signin" action="#">
<div id='container'>
<div>
<div id="divFeeTitle"></div>
</div>
</div>
</form>
I am populating the div via a container / for loop:
//go into JSON object and print out properties
for(var index=0; index<LineItem.length; index++){
DisplayTitle(LineItem[index]);
}
Display Title method does this:
function DisplayTitle(Object){
$('#divFeeTitle').html(Object.Title);
}
The trouble is, if there are 1+ objects, the divFeeTitle gets overwritten by the last object in the list. When if there are 1+ objects I need it to be laid out in order.
If I understand your issue correctly, you could try to use .append() instead of .html()
So your DisplayTitle function would look like:
function DisplayTitle(Object){
$('#divFeeTitle').append(Object.Title);
}
If you want to stop overwriting your data, be sure you save your data first:
var data = $('#divFeeTitle').html();
$('#divFeeTitle').html(data+Object.Title);
You can add an extra <br> if needed etc.

Get html content of a selector ( .html() ) with jQuery from a JavaScript variable that contains HTML

I have a javascript variable that contains a part of html code.
I need to get in this part of html code a div html content.
How can i do it ?
This is an example:
var code = '<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>';
I'd like get content of div "my_code" with Jquery .html();
How can i do it ?
Thanks
code variable it's just a string for your document. If you have parsed this HTML code inside the body then you can use $('#my_code'), otherwise it's still just a string so.. that's another story.
Check the other story here: http://jsfiddle.net/NSCQh/1/
I strongly suggest you have a look at jQuery's selector overview. They are the most important part of the jQuery magic, and without understanding them you'll get nowhere in the long run.
var html = $('#my_code').html()
or because that div containts text only
var txt = $('#my_code').text()
You've got a string, you need a DOM element. From that, you can get the jQuery object.
var el = document.createElement('div');
el.innerHTML = code;
console.log($(el));
pass the string to jquery and it works
var foo = '<div id="foo"> <span class="bar">fooBar</span> </div>';
var inside = $(foo).find('.bar').text();
alert(inside);
Create an ELEMENT, say p.
Use the following
$('<p>').append(code).find('div#my_code').html();
It create a p element, then append the content of variable code, then find div with id=my_code and select it's innerHTML.
Working model in the snippet.
var code = `<style type="text/css">
#example{
border:1px;
font-size:20px;
}
</style>
<div id="ex"> Some Content </div>
<div id="ex2"> Some Content <span> Another Content</span></div>
<div id="my_code">This Is My Code.</div><div id="ex3> Etc Etc </div>`;
var elm=$('<p>').append(code).find('div#my_code').html();
console.log(elm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JQuery get all elements by class name

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

Categories