html search and write - javascript

I have long list of links which needs to be more simple for maintaining.
For example all my (100+) urls have similar format:
AAA
BBB
as You can see different urls contains same text as name of link... so what I need is simplify things with javascript probably. Getting text between tags "> </a> and putting him inside href.:
AAA
BBB
any ideas? Thanks

So why not just store the links in an array?
$links = [
['domain' => 'web1.com', 'text' => 'AAA'],
['domain' => 'web2.net', 'text' => 'BBB']
];
foreach ($links as $link) {
echo "{$link['text']}";
}
You could even add more information to the links array, if you need.

If you have no other option you can use jQuery to select all the links and edit them.
$('a').each(function() {
var text = $(this).text()
var newTarget = $(this).attr("href") + text;
$(this).attr("href", newTarget);
});
Or, the simpler version:
$('a').each(function() {
$(this).attr("href", $(this).attr("href") + $(this).text());
});

You can do like this
// a variable with common part of the link
var link ='http://web.com/';
//get all the anchor tags. If a specific anchor tag is need pass
// indetifier like class eg-document.querySelectorAll('a.className')
var getAllAnchorTags = document.querySelectorAll('a');
/Loop through the collection
getAllAnchorTags.forEach(function(item){
// get the text in the link & concat with the common part
var creatLink =link+item.textContent;
// set href attribute to the link
item.setAttribute('href',creatLink)
})
DEMO
Edit
Let the anchor tag have a default href value. Then use getAttribute to get the href & update its value
HTML
AAA
BBB
JS
var getAllAnchorTags = document.querySelectorAll('a');
getAllAnchorTags.forEach(function(item){
var creatLink =item.getAttribute('href')+item.textContent;
item.setAttribute('href',creatLink)
})
DEMO 2

Using javascript and jquery
$(document).ready(function(){
var websites[] = "";
//Websites
websites[0] = "www.website.com";
websites[1] = "www.website.net";
var things[] = "";
//Pages corresponding to website 0
things[0] = ["AAA", "CCC"];
//Pages corresponding to website 1
things[1] = ["BBB", "DDD"];
for(x=0;x<websites.length;x++) {
for(y=0;y<things.length;y++) {
$("<a href='"+websites[x]+"/"+things[x][y]+"'>"+things[x][y]+"</a>").appendTo("#yourparentelem");
}
}
});

Related

how to use an es6 template inside of html a tag href

Hey everyone this is the first time asking a question on here. So here we go. I have a ajax request with json return. I'm trying to now take the response and dynamically create the recipe title but also create an a href with the response data.
$( window ).load( function() {
$.get({
url: window.location.href + ".json"
}).success( function( response ) {
console.log( response );
let $title = $( ".js-title" );
let reviewCount = 0;
while( reviewCount < $title.length ) {
let recipe_title = response[reviewCount].recipe.title;
let href = response[reviewCount].location.href;
$title[reviewCount].prepend( `<a>${ recipe_title }</a>` ).attr('href', `${ href }`);
reviewCount++;
}
});
});
I'm having trouble figuring out the href part of things.
Can add href in the template( while creating element ) and no need to use attr function.
example snippet to support above statement:
function prepend() {
let title = 'something';
let href = 'something/else'
$('div').append(`<a href='${href}'>${title}</a>`)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
To User stand what is wrong with what you did:
No doubt jQuery prepend method is chainable but it will return the element that it applied upon. Therefore if you open inspector you should see href is getting added in $title[reviewCount] element.
To do this correct you need to construct the a element and then prepend it.
Example snippet.
function prepend() {
let title = 'something';
let href = 'something/else';
$('div').prepend($('<a></a>').text(`${title}`).attr('href', `${href}`))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick="prepend()">Click here</button>
<div></div>
To prepend in specific element:
We need to use eq method of Jquery, again this is cahinable.
Use:
$title.eq(reviewCount).prepend($('<a>').text(`${ response[reviewCount].recipe.title }`).attr('href', http: //localhost:3000/recipes/`${recipe_id}`));

For Loops in Blogger, Replacing all characters in a string with the give character Java Script for Blogger

This is a simple question i have,
I have a simple script here :
//<![CDATA[
$(document).ready(function() {
$('img').each(function(){
var $img = $(this);
var filename = $img.attr('src')
var returnt=filename.substring((filename.lastIndexOf('/'))+1,filename.lastIndexOf('.'));
var returna=filename.substring((filename.lastIndexOf('/'))+1,filename.lastIndexOf('.'));
<b:loop values='returnt.length'>
var ctitle=returnt.replace("%2B", " ");
var calt=returna.replace("%2B", " ");
</b:loop>
$img.attr('title', ctitle);
$img.attr('alt', calt);
});
});
//]]>
I wanted all the %2B in the returnt and returna to be replace with space and stored in ctitle and calt respectively, but without a loop it won't work.
I tried something like
for(int i=0;i<returnt.length;i++)
{
var ctitle=returnt.replace("%2B", " ");
var calt=returna.replace("%2B", " ");
}
But didn't work, now I have put the values='returnt.length' in the script but it's still not working.
I know something is missing and is wrong somewhere, please tell me how to do it.
I want the loop to work like the given above for loop.
And I tried .replaceAll("","") method but didn't work. :(
I want a method to replace all the characters or info on how to write the above for loop in blogger FOR LOOP method.
You can use regex matching in replace. The code will look like -
$(document).ready(function() {
$('img').each(function() {
var $img = $(this);
var filename = $img.attr('src')
var returnt = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
var returna = filename.substring((filename.lastIndexOf('/')) + 1, filename.lastIndexOf('.'));
var ctitle = returnt.replace(/%2B/g," ");
var calt = returna.replace(/%2B/g," ");
$img.attr('title', ctitle);
$img.attr('alt', calt);
});
});
The b:loop tag is native to Blogger platform. Its values attribute only accepts data tags present in Blogger and not custom JavaScript variables. Refer to the documentation here
The general format for using loops is this:
<b:loop var='identifier' values='set-of-data'>
[repeated content goes here]
</b:loop>
The 'identifier' (i) part can be any name you choose, and will be used
to stand in for each new item in the list, each time through the loop.
The set of data you specify for the values can be any piece of data
described in the data tags article as being a list of items.

Text in dynamically generated links appears after end tag

I am generating a link dynamically using jQuery by iterating some Json data.
MyCode :
var content = "<table>";
$.each(dataArray, function( index, value )
{
content = content+"<tr><td>"+value.Version+"</td><td> Download</td></tr>";
});
content = content+"</table>";
$('#tablediv').append(content);
It should generate a table with a link in 2nd colum as:
< a href="link to url"> Download < /a>
But it generates it as :
< a href="link to url">< /a> Download
So I need text between start and end tag but it appears after end tag. How to resolve this issue?
You need to add single-quotes to your href attribute.
content += "<tr><td>"+value.Version+"</td><td><a href='"+value.Download+"'> Download</a></td></tr>";
You need to wrap value.Download in quotes:
"... Download ...";
$(document).ready(function(){
var content = "<table>";
var dataArray=[{Version:1,Download:"asdsa"},{Version:2,Download:"tete"}];
$.each(dataArray, function( index, value )
{
var $row=$("<tr>");
var $rowcellVersion= $("<td>").text(value.Version);
var $rowcellContent= $("<td>");
var $anchorTag = $("<a>").text("Download")
.attr("href",value.Download)
.appendTo($rowcellContent);
$rowcellVersion.appendTo($row);
$rowcellContent.appendTo($row);
content = content + $row[0].outerHTML;
});
content = content+"</table>";
$('#tablediv').append(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="tablediv"></div>
A bit cleaner way of handling the creation of elements .Also you can check the HTML in page inspector .It's the expected way
You can leverage jQuery if you are using it in a first place
var content = $("<table>");
$.each(dataArray, function( index, value )
{
content.append($("<tr />")
.append($("<td />").text(value.Version))
.append($("<td />").append(
$("<a />").attr("href",value.Download).text(value.Version))
);
$('#tablediv').append(content);

Javascript handle 2 data attribute

I need to use data attribute in my html
like
<div id="userlist" data-user="A.A.M"></div>
then I need to alert the data-user
I used
var userlist = document.getElementById("userlist");
var show = userlist.getAttribute("data-user");
alert(show);
My question is how to handle many data-user in the html like
<div id="userlist" data-user="A.A.M"></div>
<div id="userlist2" data-user="A.A.M2"></div>
to alert A.A.M and A.A.M2
Thanks in advance and sorry for my bad English.
You could select your elements by attribute.
$("div[data-user]").each(function() {
var user = $(this).data("user");
alert(user);
});
If you have multiple attributes per element (<div data-user='something' data-another='another'></div>), you can also access those in the same way:
$("div[data-user]").each(function() {
var user = $(this).data("user");
var another = $(this).data("another");
alert(user + ", another: " + another);
});
you know how to alert 1, alert 2:
alert at the same time:
var data1 = document.getElementById("userlist").getAttribute("data-user");
var data2 = document.getElementById("userlist2").getAttribute("data-user");
var data = data1 +"\n" + data2; //"\n" can be other separators you like
alert(data)
if you have many of them, you can use jQuery:
add this in your , before any other js code.
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
then :
$("div[id^=userlist]").each(function(){
alert($(this).attr("data-user"));
});
Calling getElementById on both should work. If you want to iterate you can try to use getElementsByTagName or getElementsByClassName. If you want to select any arbitrary element with the attribute data-user, you can either use querySelectorAll, or check out jQuery, and use $("[data-user]") as a selector.
Does that answer your question?

add dynamic id to links using Javascript?

I have many links on a page generated dynamically. Now I want to attach ids to them based on a link just before them.
I have written the following function to return me the value I want to add as id to the href I want.
<script>
function movingid(){
var res = location.href.replace(/.*student\/(.*)\/subject/, '$1');
var subjectid = res.split("/")[2];
var classid = res.split("/")[1];
var sectionid = res.split("/")[0];
return classid+"-"+sectionid+"-"+subjectid;
}
</script>
So what I did is
<a href="javascript:void(0);" id= "javascript:movingid();" >Move To</a>
But the HTML thus generated is not calling the function. Instead its adding the id as plain text form like this id= "javascript:movingid();". How can I call the function?
Please help
Create the links this way:
<a href="javascript:void(0);" id= "" >Move To</a>
Maybe wrapping the links with a div, which gets the id "mylinks". After this call a function adding the id with this code:
i = "1";
$( "div#mylinks a" ).each(function( index ) {
$(this).attr("id",i);
i++;
});
Instead of i take your code from the movingid function you already posted.

Categories

Resources