How to retrieve value in jquery - javascript

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>

Related

select a string after a substring in an element's class name

I have an element that contains an input text, to get the input text I'm using the jQuery method find.
The input text has a class name like this page-id-x with the x is variable, so I want to select that number after the substring page-id, and this is what I tried :
var id = ui.item.find('input').attr('class').split(/\s+/).filter(function(s){
return s.includes('page-id-');
})[0].split('-')[2];
console.log(id);
I think this code is too complicated, but I couldn't figure out some other way to do it.
If someone knows a better way, I'll be thankful.
Thanks in advance.
I'm going to assume the x part of page-id-x, not the id part, is what varies (since that's what your code assumes).
Another way to do it is with a regular expression, but I'm not sure I'd call it simpler:
var id = ui.item
.find('input')
.attr('class')
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
Example:
var ui = {
item: $("#item")
};
var id = ui.item
.find('input')
.attr("class")
.match(/(?:^|\s)page-id-([^- ]+)(?:\s|$)/)[1];
console.log(id);
<div id="item">
<input class="foo page-id-23 bar">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The above makes the same assumptions your current code does, which are:
The first input in ui.item is the one you want
It will have the relevant class name
I assume those are okay, as your question is asking for an alternative, suggesting what you have is working.
As you're using jQuery, take a look at this: https://api.jquery.com/category/selectors/attribute-selectors/
For your case, you can use $('[class^="page-id-"'). These types of selectors (listed on the link above) actually work in CSS, too. (At least most should, if not all.)
To get the number after page-id-, my suggestion would be to store that number in some other HTML attribute, like data-pageID="1" or the like.
So you could have:
<div id="page-id-3" data-pageID="3">CONTENT</div>
Then, when you have the DOM element using $('[class^="page-id-"'), you can access that number with .attr('data-pageID').val().
If you can control the HTML markup, instead of using class names, you can use data attributes instead. For example, instead of:
<input class="page-id-1">
You can use:
<input data-page-id="1">
Then jQuery can find this element effortlessly:
$('[data-page-id]').attr('data-page-id')
You can find your element using the *= selector.
let elem = document.querySelector('[class*=page-id-]')
Once you have the element, you can parse the id out:
let [base, id] = elem.className.match(/page-id-(\d+)/)
console.log('page id: %s', id);

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

jQuery .find() with an iD

JS:
this.par = $(this).find("p");
HTML:
<p></p>
The problem is that I dont want to find p tag, but rather a div with a specific ID like this one below.
<div id="abc"></div>
Use the ID selector:
var myDivObj = $("#abc");
Take a look at the list of jQuery selectors.
Additional Information:
It's difficult to tell by your code what you're trying to do, but based on what you've posted, there is no reason to use $(this). The ID selector alone should meet your needs.
Well, you can just use the id selector:
$(this).find('#abc');
Since ids should be unique on the page, you may as well just use it as the constructor:
$('#abc');
If this isn't exactly the same, you're doing something wrong.
this.par = $(this).find("#abc");
You don't want to do that. Don't add properties to the html elements. This is better:
var par = $(this).find('#idOfElement')
Storing the result in this.par is a very bad idea, since this refers to a DomElement.
What you might be looking for is jQuery .data():
$(this).data('par', $(this).find('#idOfElement'))
Which allows you to associate #idOfElement with this.
use id selector
this.par = $(this).find("#abc");
but id is uniqe you can remove $(this).find and use this code
this.par = $("#abc");

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

Find and assign content to a variable

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>

Categories