How to extract all hyperlink titles from big html string using javascript? - javascript

I got an HTML string as :var code; I want to extract all hyper link title values in this big string and place them in textarea. I tried the following but it never works. could any one tell me what i am doing wrong?
sample hyperlinks to look for(i want to extract mango,cherry,...) :
mango
cherry
my code string has blocks of data like below:
<div class="details">
<div class="title">
mango
<span class="type">3</span>
</div>
</div>
full code:
$.getJSON('http://anyorigin.com/get?url=http://asite.com/getit.php/&callback=?', function(data){
//$('#output').html(data.contents);
var siteContents = data.contents;
//writes to textarea
document.myform.outputtext.value = siteContents ;
var start = siteContents.indexOf('<ul class="list">');
var end = siteContents.indexOf('<ul class="pag">', start);
var code = siteContents.substring(start, end);
document.myform2.outputtext2.value = code ;
var pattern = /<a href="([^"]+?)">([^<]+?)<\/a>/gi;
code = code.match(pattern);
for (i = 0; i < code.length; i++) {
document.write($2<br />'));
}
});
</script>

It looks like you're trying to parse HTML with regex. This post has some more info on that topic.
Since this question is tagged as jQuery, you could try something like the following...
Make a jQuery object out of the returned HTML:
$markup = $(data.contents);
Find the anchors:
$anchors = $markup.find('a');
Get the text (or whatever attribute you want from it):
arrText = [];
$anchors.each(function() {
arrText.push($(this).text());
});
Put result into textarea:
$textarea.val(arrText.join(','));

To achive this jquery is the simplest solution, you can try below code
$('a').each(function(){
var copiedTitle = $(this).html();
var previous = $('#test').html();
var newText = previous +"\n"+ copiedTitle;
$('#test').html(newText);
});
JS Fiddle

Related

JS exstract part of URL from multiple form fields

I have a form that has multiple fields all with the same class. These are populated with URL's that follow the same structure. I am trying to extract the same section from each URL. So far var res = x.split('/')[5]; will achieve this but only for the first URL. I can also use var x = document.querySelectorAll(".example") to change all the url's but I cannot find the correct way to combine both of these function. so far my code looks like this:
script>
function myFunction() {
var x = document.querySelectorAll(".example").innerHTML;
var res = x.split('/')[5];
var i;
for (i = 0; i < x.length; i++) {
x[i].innerHTML = res;
}
}
</script>
I have looked around but can't find a solution that fits. Thanks in advance for your help.
So loop over the HTML Collection, this is making assumptions based on code.
// Find all the elements
var elems = document.querySelectorAll(".example")
// loop over the collection
elems.forEach(function (elem) {
// reference the text of the element and split it
var txt = elem.innerHTML.split("/")[5]
// replace the text
elem.innerHTML = txt
})
<div class="example">1/2/3/4/5/a</div>
<div class="example">1/2/3/4/5/b</div>
<div class="example">1/2/3/4/5/c</div>
<div class="example">1/2/3/4/5/d</div>
<div class="example">1/2/3/4/5/e</div>
<div class="example">1/2/3/4/5/f</div>

Hashing element contents in-place with Crypto-js

I am trying to hash data using JavaScript. When I run the first code it will hash using document.write. Now I try the second code to hash by content id it didn't work. Can anyone explain why?
<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
<script>
var hash = CryptoJS.SHA256("hello");
document.write(hash.toString(CryptoJS.enc.Hex));
</script>
using this first method will work very fine
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
<script>
var hash = CryptoJS.SHA256;
var it = (hash.toString(CryptoJS.enc.Hex));
document.getElementById('hashit').innerHTML = 'it';
</script>
<p id="hashit">Hello</p>
If you want to hash something in-place in an element then you need to read out the value/text, hash it and write the text back:
var element = document.getElementById('hashit');
var hash = CryptoJS.SHA256(element.innerHTML);
element.innerHTML = hash.toString();
Here is a runnable snippet which changes the value after 2 seconds.
setTimeout(function(){
var element = document.getElementById('hashit');
var hash = CryptoJS.SHA256(element.innerHTML);
element.innerHTML = hash.toString();
}, 2000);
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/sha256.js"></script>
<p id="hashit">Hello</p>
Keep in mind that JavaScript is not like PHP. You can't simply use variables in strings like this element.innerHTML = 'it';. You have to useelement.innerHTML = it;.

Get specific value from a HTML output

I am getting the following result from a data source.
"<span class=\"highlight\">DSDT10</span><div>011XBY</div>"
The value in span and div could vary.
And I want only the value inside the span "DSDT10" in a separate variable.
What I have tried:
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.replace(/<\/?span[^>]*>/g, "");
$('#output').append(formattedData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Expectation:
Retrieve only "DSDT10" from the data variable.
Any suggestion is appreciated. Thanks.
You just want to get the text within the span? You could modify your regex a bit and use a match..
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.match(/<span[^>]*>([^<]*)<\/span>/, "")[1];
But since you're using jquery you could also just do this:
var formattedData = $("<div>", {html: data}).find("span").text()
Only two lines of code:
_str = "<span class=\"highlight\">DSDT10</span><div>011XBY</div>";
_span = $(_str).filter('span').text();
It's enough only one line:
$('#output').html($('span').html());

Having trouble appending javascript into my html

OK,so I am trying to pull some data from an api. The problem that I have run into is that I am able to find out the information that I am looking for, but am having trouble getting that information out of the console and onto my main index.html page.
Here is my JS code
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
$.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
console.log(info);
});
});
});
Here is my html code
<div id="search">
<h1>API Test</h1>
<input type="search" id="search-keyword">
<button id="myBtn">Try it</button>
</div>
<div id="results"></div>
By doing this, I am able to get pretty much what I am looking for. However I cannot get the data from the console to the actual page.
I have tried appendChild
var bob = document.getElementById(results);
var content = document.createTextNode(info);
bob.appendChild(info);
I have tried innerHTML
var theDiv = document.getElementById(results);
theDiv.innerHTML += info;
..and I have tried .append()
$('#myBtn').click(function() {
$(results).append(info)
})
I'm out of ideas. I realize that I probably have a small problem somewhere else that I am not seeing that is probably the root of this. Much thanks to anyone who can help me with this issue.
"results" needs to be in quotes with regular javascript and for jquery you have already decalred the results variable.
var theDiv = document.getElementById("results");
theDiv.innerHTML += info;
$('#myBtn').click(function(){
results.append(info)
})
Also since you are declaring results outside of your document ready call you have to make sure you html comes before the javascript.
<script>
var form = $('#search');
var input = $('#search-keyword');
var results = $('#results');
$(document).ready(function() {
$("#myBtn").on('click', function() {
var symbol = $("#search-keyword").val();
var resultedData = $.getJSON("http://dev.markitondemand.com/Api/v2/quote/jsonp?symbol=" + symbol + "&callback=?", function(info) {
return info;
});
var resultDiv = document.getElementById("results");
resultDiv.innerHTML += resultedData;
});
});
</script>

Vanilla JavaScript For Loop to push array of names

Mock Mark up:
<div class="post">
<a name="1234"></a>
</div>
Remember this is mock markup of course there is more html in the above, this a is the first a tag inside the parent .post
Here is my code:
var pid = [];
var post = document.getElementsByClassName('post');
for(var i=0;i<post.length;i++){
var postId = post[i].getElementsByTagName('a')[0].getAttributeNode('name');
pid.push(postId);
}
alert(pid);
I keep getting literally ,,,,,,
I have tried .getAttribute and .getAttributeNode
Is there something I am doing wrong here? I am trying to make an array of "names" persay to classify these later on using an ID specification.
Any suggestions thank you!
You did everything right but you forgot the .value:
var pid = [];
var post = document.getElementsByClassName('post');
for(var i=0;i<post.length;i++){
var postId = post[i].getElementsByTagName('a')[0].getAttributeNode('name').value;
pid.push(postId);
}
alert(pid);
FIDDLE
You can use .value as Tom mentioned or you can use .getAttribute('name').
You would need to modify your code a little bit further for it work for more than one anchor in .post class:
<div class="post">
<a name="1234"></a>
<a name="5678"></a>
<a name="9123"></a>
</div>
JavaScript:
var pid = [];
var post = document.getElementsByClassName('post');
for(var i=0;i<post.length;i++){
var anchors = post[i].getElementsByTagName('a');
for(var j=0; j<anchors.length; j++){
var name = anchors[j].getAttribute('name');
pid.push(name);
}
}
for(var i=0;i<pid.length;i++){
alert(pid[i]);
}
http://jsfiddle.net/joybroto/3d9qz/7/

Categories