Javascript debugging: Printing out the element retrieved from a jQuery selector - javascript

I want to get an HTML element with a jQuery selector and print out all its contents (either in an alert or console debug). Something like this...
<div class="mydiv">Hello is it me you are looking for?</div>
<script>
alert("But I still haven't found what I am looking for " + $("#mydiv").html());
</script>
I also tried printElement as suggested in this post, but that doesn't seem to work either.
Here is a simple fiddle.

The # is the id selector. You have a class (<div class="mydiv">) so you need to use the class selector .:
alert("But I still haven't found what I am looking for " + $(".mydiv").html());

Wrap the content for which you want to print HTML element.
<div id="myHtml">
<div class="mydiv">Hello is it me you are looking for?</div>
</div>
<script>
alert($("#myHtml").html())
</script>

Related

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>

How to append just before the end of the BODY tag using JQuery [duplicate]

I have this HTML:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
</div>
and want to add more divs after the strong element to result:
<div class="region-list" id="region_North_America">
<strong>North America</strong>
<div> ... </div>
<div> ... </div>
<div> ... </div>
</div>
I am trying this:
var row_str = '<div>content here</div>';
$('#region_North_America div:last').html(row_str);
However, there is no change to the html. This is probably so since there is no div within the element selected.
I know that the js is making it to this code because I can print the content of row_str to the console.
So, how can I get to the end of that container element to add the new items?
Thx.
Try:
$("#region_North_America").append(row_str);
using append().
Or:
$("<div>content here</div>").appendTo("#region_North_America");
To create the element on the fly, and place it in the document.
Using the appendTo method.
Your code will just place html in the last div within #region_North_America. Use the append function.
$("div.region-list").append(row_str);

How to .append text to a div using jQuery?

I'm trying to append a piece of text to a div using jQuery. I try to do this using the following code:
<html><head></head><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendButton").click(function(){
$("#conversation").append("<P>This is a message");
});
});
</script>
<div class="conversation"><p>some message</div>
<form><input type="button" id="sendButton" value="Send Message"></form>
</body></html>
Seeing the multitude of tutorials on the subject it seems to be such a simple thing to do, but I can't seem to figure out what I'm doing wrong here. Any help would be greatly appreciated.
You need to use class selector, As #conversation referes to element with id conversation
$(".conversation").append("<P>aergerag");
Fiddle DEMO
EDIT
You should look at this To Close or Not To Close Tags in HTML5 and a good question Closing tags in HTML5
replace # with . in your selector (conversation is a CLASS)
$(".conversation").append("<P>aergerag");
I am not any good at jQuery but from one of my projects I had to simply target the div with html as:
var someData = "This is a message";
$("#conversation").html(someData);
If some contents exists before this, then you can retrieve them, concatenate, and write it back into the target div.

Jquery remove everything except for bolded

I have html like this:
<div id="divTestArea1">
<b>Bold text</b>
<i>Italic text</i>
<div id="divTestArea2">
<b>Bold text 2</b>
<i>Italic text 2</i>
<div>
<b>Bold text 3</b>
</div>
</div>
and I would like to remove all elements that aren't bold. I've tried with this code:
$('*:not(b)').remove();
and a couple other variations but they all either error out or remove everything. btw, are jquery selectors and jsoup selectors 100% compatible? I'd like to use the answer to this in jsoup as well.
Your current code removes the document <body> as well as all <div>s which contain the <b> tags. If you only want to save the bold text then Shih-En Chou's solution works well. If you want to save the <div> structure that the <b> tags are in as well you could do this:
$("body *:not(div, b)")​​​​.remove();​
DEMO
My solution:
I clone <b> and save it into memory.
->Remove all
-> insert <b> into <body>
here is my code:
http://jsfiddle.net/sechou/43ENq/
$(function(){
var tmpB = $("b").clone();
$('body').remove();
$("body").append(tmpB);
});​
Move all elements in #divTestArea2 as it is a div and will be removed as well to #divTestArea1, then filter out anything that is'nt a <b> and remove it :
$("#divTestArea1").append($("*", "#divTestArea2")).find('*').filter(function() {
return this.tagName !== 'B';
}).remove();
FIDDLE
The above keeps the #divTestArea1 element intact, to remove everything but the <b> elements, something like :
$('body')​.append($('b'))​.find('*')​.not('b')​.remove();​
FIDDLE
I prefer .detach().
var $body = $("body");
var $b = $("b", $body).detach();
$(":not(b)", $body).remove();​​​​​​​​​​​
$body.append($b);
This way you don't need to either move or clone anything to overcome the problem of the deletion of the objects wrapping your <b/> elements.
(demo)
Try this:
// Find all the <b> tags and unwrap them so they all become siblings and finally
// remove non <b> siblings
$('body').find('b').unwrap().siblings('*:not(b)').remove();
Demo: http://jsfiddle.net/3f2Hu/

Select a body within a div with jQuery

I have an element (for example, a body) nested somewhere inside a div.. Something like:
<div class=wrapper>
..
..
<body>
</body>
</div>
How would I go about selecting the body with jQuery?
As others have said - this doesn't look like valid HTML - I'm going to assume that you just gave that as an example as this technique can be used to find any type of element.
This should do the trick to locate the body tag -
$('div.wrapper').find('body')
When you don't specify in your selector that you are talking about a class . or id # attribute - the whole string will be matched to the type of element.
The same could be done for -
<img> tags -
$('div.wrapper').find('img')
<a> tags -
$('div.wrapper').find('a')
<span> tags -
$('div.wrapper').find('span')
etc...
Your HTML Markup is off, first of all.
<body>
<div class="wrapper">
<div class="body">
..
..
</div>
</div>
</body>
Select it with $('div.wrapper div.body')
Thanks to ClarkeyBoy for pointing out my mistakes, fixed my post.
It doesn't look like valid HTML, but try this:
$('div.wrapper body')
Surely that HTML isn't correct to have a body tag within a div? Unless it's inside an iframe?
However you could use this to select the body tag...
jQuery("div.wrapper body").whatever();

Categories