Html href javascript jquery

Get href value of an anchor tag with JavaScript/jQuery

This post will discuss how to get the href value of an anchor tag in JavaScript and jQuery.

1. Using jQuery

In jQuery, you can use the .prop() method to get the href value of an anchor tag. This is demonstrated below:

JS

HTML

To get the text of an anchor element, use the .text() method.

JS

HTML

2. Using JavaScript

In vanilla JavaScript, you can use the querySelector() , which will return the first anchor tag within the document. Then we can directly access the href property to get the exact value of the href attribute. The following code demonstrates this.

JS

HTML

This can also be done using the getAttribute() method, which gets the value of the href attribute on the specified anchor tag.

JS

HTML

That’s all about getting the href value of an anchor tag in JavaScript and jQuery.

Читайте также:  Java convert enum list to string list

Average rating 4.41 /5. Vote count: 37

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂

This website uses cookies. By using this site, you agree to the use of cookies, our policies, copyright terms and other conditions. Read our Privacy Policy. Got it

Источник

Изменение атрибута href для гиперссылки с использованием jQuery

Abstract representation of modifying hyperlink attributes using jQuery.

Иногда веб-разработчики сталкиваются с задачей изменения целевого адреса гиперссылки в процессе работы веб-страницы. Это может быть необходимо, например, при создании динамического контента, когда ссылка должна вести на разные страницы в зависимости от действий пользователя.

Для решения такой задачи можно использовать популярную библиотеку JavaScript — jQuery. С ее помощью изменить атрибут href гиперссылки становится легко и просто.

Вот базовый пример HTML-страницы с гиперссылкой:

Гиперссылка ведет на сайт https://example.com . Но что, если необходимо изменить целевой адрес этой ссылки?

Для этого можно воспользоваться методом jQuery .attr() , который позволяет получать или устанавливать значения атрибутов элементов.

Сначала следует подключить библиотеку jQuery к странице:

Затем можно применить метод .attr() к нужной гиперссылке. В данном случае, гиперссылка имеет идентификатор mylink , поэтому код будет выглядеть следующим образом:

$("#mylink").attr("href", "https://newsite.com");

Таким образом, после выполнения этого кода, гиперссылка будет вести на https://newsite.com .

Решение такой задачи с использованием jQuery довольно простое и не требует глубоких знаний в области JavaScript. Это делает jQuery удобным инструментом для веб-разработчиков разного уровня.

Источник

Javascript jquery add href tag in html

Solution 3: with native javascript you could put in a «not random» link and randomize it with the setAttiribute method native to JavaScript note that with older versioned browsers selecting the object becomes harder so getElementById is one of the few ways that is safe along most of the browsers. Solution 1: Try this Solution 2: This code should sort your problem out: Solution 3: If, say, you didn’t have the text of the number as part of the link, I like to encode values like this into the id, which would give you this: Solution 1: You can use attribute selector of jquery to get and set the href Solution 2: This can be easily done with jQuery.

Add href to .text output in jquery

To avoid XSS attacks (among other weird problems), append an anchor element and set its text. This means you don’t have to worry about escaping anything.

If your HTML gets much more complicated, might I suggest a JavaScript template engine? I use Swig for most projects, but there are many choices.

you have to use append() , or html()

$('#winners').append('Winner:' + ' ' + message.userName + ' ' + ' '+ 'score:' + ' ' + message.score + ' ' + ' '+ 'Start time:' + ' ' + message.startTime + ' ' + ' '+ 'End time:' + '' + message.endTime ); 

this may help you to understand better :

Both @Brad and @ProllyGeek are correct — but @Brad’s solution is best given the potential risk of XSS attacks. Here is his code, just cleaned up a bit for better readability. 🙂

$('#winners').append([ 'Winner: ', $('') .attr('href', 'scoreTracker.php?id=' + encodeURIComponent(message.userId) .text(message.userName + ' score: ' + message.score + ' Start time: ' + message.startTime + ' End time: ' + message.endTime) ]); 

Jquery — Adding a javascript variable to html, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

Add some javascript inside a html anchor tag href element

If «fit this in with the Html» means «add a random number to every link that looks like this» , then something like this would do it:

$("a[href^=includes/jwplayer/player.swf]").attr("href", function (i, s) < return s.replace( /\?\d*&?/, "?" + Math.floor(Math.random() * 1000) + "&" ); >) 
\? # a question mark \d* # any number of digits (to replace what's already there) &? # an optional ampersand 

You could set it via client script, but this will break if the user has JavaScript turned off. It would be better to set it from the server side, which sounds like PHP in your case.

with native javascript you could put in a «not random» link and randomize it with the setAttiribute method native to JavaScript

var r = Math.floor(Math.random() * 1000); document.getElementById('an-id-of-the-link').setAttribute('href', 'includes/jwplayer/player.swf?' + r + '&file=nicki.mp4'); 

note that with older versioned browsers selecting the object becomes harder so getElementById is one of the few ways that is safe along most of the browsers.

How to dynamically add anchor/href in jQuery, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams

JQuery Add HTML and Event

for (i = 0; i < totalPages; i++) < var newDiv = $("").append(i+1).click(function() < alert(this.text); >); $('#pageLinks').append(newDiv).append(" "); > 

This code should sort your problem out:

for (i = 0; i < totalPages; i++) < var newDiv = $("") .append(i+1) .click( function() < alert($(this).html()); >); $('#pageLinks').append(newDiv).append(" "); > 

If, say, you didn’t have the text of the number as part of the link, I like to encode values like this into the id, which would give you this:

    

Html — Adding tag href with Javascript doesn’t work, Thanks for all responses. I found a solution that works in my case, and the important thing was to not add the BASE-tag itself with JavaScript, instead …

Extracting and replacing href tag using javascript or JQuery

You can use attribute selector of jquery to get and set the href

$(".product").attr("href",$("product_prev").attr("href")); 

This can be easily done with jQuery.

var first_href= $(".product_prev").attr('href'); $(".product").attr('href', first_href); 

Jquery — Adding HTML tag with javascript, Last call to make your voice heard! Our 2022 Developer Survey closes in less than a week. Take survey.

Источник

Перенаправление на другую веб-страницу с помощью JavaScript/jQuery

В этом посте мы обсудим, как перенаправить на другую веб-страницу в JavaScript и jQuery.

Существует несколько способов перенаправления страницы в JavaScript, каждый из которых включает использование window.location имущество. Он возвращает Location объект, представляющий местоположение (URL) текущего документа.

1. Использование location.href

Когда вы назначаете URL для window.location.href связанный документ переходит на новую страницу из того же или другого источника.

С window является глобальным объектом, его можно сократить до:

Обратите внимание, что location является синонимом location.href . Таким образом, вы можете напрямую присвоить значение location объект.

2. Использование location.assign() функция

Вы также можете перейти к новому URL-адресу, используя location.assign() метод. Если указанный URL-адрес имеет другое происхождение, это может привести к сбою из-за политики CORS.

Обратите внимание, что assign() метод сохранит текущую страницу в истории сеанса, т.е. пользователь может вернуться назад с помощью кнопки «Назад».

3. Использование location.replace() функция

Существует еще один метод объекта местоположения, который называется replace() , который заменяет текущий документ документом по указанному URL-адресу. в отличие от assign() метод, это заменяет запись истории сеанса, и пользователь не может вернуться на исходную страницу с помощью кнопки «Назад».

Источник

The attr() method will change the href of all hyperlinks to point to Google. For instance, you have a mix of link source and link target anchor tags:

And you don’t want to add href attributes to them. Then, you can specify the selector to match the tags with an existing href attribute:

In case you want to match an anchor with a specific existing href, then you can do the following:

html> html> head> title>Title of the document title> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"> script> head> body> a href="www.example.com">Link a> script> $("a[href]").attr("href", "https://www.w3docs.com"); script> body> html>

Then you should update only some part of the href attribute:

$("a[href^='http://w3docs.com']") .each(function () < this.href = this.href.replace(/^http:\/\/beta\.w3docs\.com/, "http://w3docs.com"); >);

The first part only selects links where the href starts with http://stackoverflow.com. Then, a function is specified, which uses a regular expression to replace this part of the URL with a new one.

The attr() Method

The .attr() method is used to get the attribute value for the first element in the matched set. To get the value for each element, the looping construct methods, namely — .each() or .map() methods of jQuery are used.

One of the main benefits this method suggests is that it can be called directly on a jQuery object and chained to other methods.

Источник

Оцените статью