Find and assign content to a variable - javascript

What I need is to find an element which have class="selected" and than assign content of that element to a variable.
This is the content
This is the content
This is the content
Any help? Thank you

Use the class operator:
var elementContents = $('.selected').html(); //assuming there is only one element found with the class selected
Hope this helped.

var someContent = $('.selected').html();

var variable=$(".selected").text();
DEMO

Give it an Id, then use:
var content = document.getElementById("yourIdHere").innerHTML;

to ensure you only get the first occurance, don't forget to instruct jQuery to only get the first, and to ensure it's readable i'd use the .text() not the .html() selector as it will strip any HTML away if there is any
This is the content
This is the content
This is the content
<script type="text/javascript">
$(document).ready(function() {
var myVariable = $(".selected").first().text();
});
</script>

Related

Get element which have a specific data-* set

Say, I've a <script data-src = "script.js"> somewhere in my DOM without any id or other identifiable attribute set. How could I select that element so that I can reset that element with correct src.
Like:
var el = //code
el.src = el.dataset.src;
Maybe I could loop all script tag and all, but is there a way to get specific element by just this info?
EDIT:
With pure javascript.
you can use query selector as following :
element = document.querySelectorAll("script[data-src]")[0];
This can be done with JavaScript's querySelectorAll()
// Get the first script tag with the data attribute "data-src"
var theScript = document.querySelectorAll("script[data-src]")[0];
// write the data-src to the document
document.write(theScript.getAttribute('data-src'));
<script data-src="testing.js"></script>
Use $(document).find('[data-src]') to get the object. Note, if you have more objects with data-src then you have to loop through them.
$(document).find('script[data-src]').attr("data-src", "News link")
console.log($(document).find('script[data-src]').data("src"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-src="script.js"></script>
Try this...
with pure Js.
var el=document.querySelector('script[data-src]');
console.log(el.dataset.src);
el.dataset.src='correct-src.js';
console.log(el.dataset.src);
<script data-src = "script.js">
</script>
<div></div>
jQuery:
$("script[data-src='script.js']")
For more details https://api.jquery.com/category/selectors/
Javacript:
document.querySelector('[data-src="script.js"]')
Form more details see here

jQuery method to obtain contents of H2 Tag

I have the following HTML:
<div id="new_subscribed_threads" class="block">
<h2 class="blockhead">Subscribed Threads with New Posts: (0)</h2>
I am using the $.get method to obtain the content of another page on the same server. I want to store the contents of the H2 Tag in a variable and I am confused about how to get the H2.
I tried this:
var MyVar = $(results).find("new_subscribed_threads.h2").html();
But I don't think I am on the right track.
is should be like this:
var MyVar = $(results).find("#new_subscribed_threads h2").html();
or
var MyVar = $(results).find("h2.blockhead").html();
But I don't think I am on the right track.
Yes, you're totally off actually. You don't want to use a class selector .h2, but
an id selector
descendant syntax
and an element selector
It is as simple as this:
Find the position of the h2 tag
Access it and get the content via html()
It looks something like:
var s= $('div.block >h2').html();
console.log(s);

How to set the title attribute of an element with not just a string?

I want to set the title attribute of an element with some html. For eg:
<div id="element"></div>
$("#element").title = $("#menu");
where
<div id="menu">
Link
</div>
This does not render the menu in the title. Can this be done?
Use attr() like
var title = $("#menu a:first").attr('href');
$("#element").attr('title',title);
Demo here
If you want to insert the html contents of one element into another, you can use this.
$("#element").html($("#menu").html());
BTW, this doesn't deal with title at all.
If I understand you correctly then NO, you cannot display HTML using the title attribute. Depending on what you are trying to do, you better find and use a jQuery tooltip or menu plugin. The jQuery UI library has both.
Try this:
var html_string = $("#menu a:first").prop('href');
$("#element").prop('title', html_string );
you can use
var val = "<p>This is my new title</p>"
document.getElementById('element').setAttribute("title",val);
You can set html inside an attribute, but it will not display as renderable html.
$("#element").attr("title", $("#menu").text());

Why jQuery selector is not working?

Why is this not working?
$(document).ready(function(){
var content = 'News';
$("#test").replaceWith(function(){
return content;
});
//Here is the problem. I don't know why but I can't define adres.
var adres = $("#test .ot-origin-anchor").attr("href");
//find example.com - ugly :P
var adresRegExp = adres.match(/(\w+:\/\/+(www.|))([^/]+)/);
alert(RegExp.$3);
});
</script>
<div id="test">bnb</div>
After the .replaceWith() call, there is no element on the page with ID test. It looks like you meant to use .html() or .append() instead of .replaceWith().
var content = 'News';
$("#test").html(content);
// or
$("#test").append(content);
var adres = $("#test .ot-origin-anchor").attr("href");
replaceWith replaces every element in the selection to which it is applied. That would mean you'd end up with just content after the replace. So your next query, which looks for #test would match nothing. #test is gone. You replaced it with content.
You are replacing #test with your content variable so the selector isn't finding an element with id test. Try $("#test").html(content); instead.
Updated jsfiddle: http://jsfiddle.net/sHGrB/
Why use replace with? Use the jQuery .html() method to add it to the DOM, after that, you should be able to select it easily. Working Example.
If you replace:
$("#test").replaceWith(function(){
return content;
});
with:
$("#test").html(content);
You will get you the results you want, because #test no longer exists with replace
There are a couple problems here, one is that replaceWith is actually replacing #test with content. Then, your selector is looking for #test .ot-origin-anchor which doesn't exist, because #test was clobbered. Instead you should do something like:
$(document).ready(function(){
var content = 'News';
$("#test").html(content);
var address = $("#test .ot-origin-anchor").attr("href");
var addressRegExp = address.match(/(\w+:\/\/+(www.|))([^/]+)/);
alert(RegExp.$3);
});

How to retrieve value in jquery

In my js I have a var in which I have stored innerHTML.
The var is having value something like
<h2>headline</h2>
<div>....</div>
...........
Now I want to retrieve value of h2 tag..what I am doing is
$(myvar).find("h2").text()
but its not working...what should be the exact syntax?
EDIT:
alert(myvar)=<h2>headline</h2>
<div>....</div>
Thanks.
The find method will not work for this case, because it gets the descendants of each element in the current set of matched elements (the h2 and the div in your example).
You can simply use filter (available on jQuery 1.3.2):
var myvar ="<h2>headline</h2>" +
"<div>....</div>";
alert($(myvar).filter('h2').text()); // headline
Check an example here.
Find() returns a collection of nodes. Use first():
h2text = $(myvar).first("h2").text();
Change your HTML to something like this.
<div>
<h2>headline</h2>
<div>....</div>
</div>
generally would make more sense to wrap the contents of your var in a div as proposed by ChaosPandion.
if that's not possible, you can try this...
<script>
var myVar = '<h2 id="test">heading</h2><div>stuff</div>';
var jVar = $(myVar);
alert($(jVar.get(0)).text());
</script>

Categories