Как добавить target = ”_ blank” к ссылке с помощью jQuery?

Опубликовано: 11 Декабря, 2021

Учитывая тег привязки внутри элемента DIV, задача состоит в том, чтобы добавить target = ”_ blank” к элементу привязки. Ниже описаны два метода решения этой проблемы:

Подход 1:

  • Выберите внешний элемент DIV элемента привязки.
  • Используйте метод .attr (), чтобы установить для целевого свойства значение «_blank» элемента привязки.

Как проверить все атрибуты любого элемента в строке:

  • Сначала выберите элемент.
  • Используйте метод .attributes, чтобы получить доступ ко всем атрибутам элемента.
  • Используйте конкатенацию строк, чтобы добавить в строку каждый атрибут и его значение.

Пример: этот пример реализует вышеупомянутый подход.

<!DOCTYPE HTML>
< html >
< head >
< title >
How to add target="_blank"
to a link using jQuery ?
</ title >
< script src =
</ script >
</ head >
< body style = "text-align:center;" >
< h1 style = "color: green" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 20px; font-weight: bold;" >
</ p >
< div id = "outer" >
< a id = "a" href = " https://www.geeksforgeeks.org " >
THIS IS LINK
</ a >
</ div >
< br >
< button onclick = "gfg_Run()" >
Click Here
</ button >
< p id = "GFG_DOWN" style = "color:green;
font-size: 26px; font-weight: bold;">
</ p >
< script >
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = 'Click on the button to add'
+ ' target="_blank" to the link.';
// This function only returns all attribute
// properties of DOM element as a string and
// has nothing to do with the target property
function getAttr() {
var elmt = document.getElementById("a");
// Adding the every attribute to the string.
for (var i = 0, attr = elmt.attributes,
n = attr.length, str = ""; i < n ; i++) {
str = str + attr[i].nodeName + "='"
+ attr[i].nodeValue + "'<br>";
}
// Returns the atring of attributes
return str;
}
el_down.innerHTML = getAttr();
function gfg_Run() {
// Set the target property to '_blank'.
$('#outer a').attr('target', '_blank');
el_down.innerHTML = getAttr();
}
</ script >
</ body >
</ html >

Выход:

  • Перед нажатием на кнопку:
  • После нажатия на кнопку:

Подход 2:

  • Сначала выберите внешний DIV, а затем внутренний элемент привязки с помощью методов document.getElementByID () и document.getElementsByTagName () соответственно.
  • Используйте метод .setAttribute ('target', '_blank'), чтобы установить целевой атрибут.

Как увидеть все атрибуты любого элемента в виде строки:

  • сначала выберите элемент.
  • Используйте метод .attributes, чтобы получить доступ ко всем атрибутам элемента.
  • Используйте конкатенацию строк, чтобы добавить в строку каждый атрибут и его значение.

Пример: этот пример реализует вышеупомянутый подход.

<!DOCTYPE HTML>
< html >
< head >
< title >
How to add target="_blank"
to a link using jQuery ?
</ title >
</ head >
< body style = "text-align:center;" >
< h1 style = "color: green" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" style =
"font-size: 20px; font-weight: bold;" >
</ p >
< div id = "outer" >
< a id = "a" href = " https://www.geeksforgeeks.org " >
THIS IS LINK
</ a >
</ div >
< br >
< button onclick = "gfg_Run()" >
Click Here
</ button >
< p id = "GFG_DOWN" style = "color:green;
font-size: 26px; font-weight: bold;">
</ p >
< script >
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = 'Click on the button to add'
+ ' target="_blank" to the link.';
// This function returns all attribute properties
// of DOM element as a string and has nothing
// to do with the target property
function getAttr() {
var elmt = document.getElementById("a");
for (var i=0, attr=elmt.attributes,
n=attr.length, str = ""; i< n ; i++){
str = str + attr[i].nodeName + "='"
+ attr[i].nodeValue + "'<br>";
}
return str;
}
el_down.innerHTML = getAttr();
function gfg_Run() {
// Getting the anchor element inside the outer DIV.
var el = document.getElementById('outer')
.getElementsByTagName('a');
for (var i = 0; i < el.length ; i++){
// Set the target property of every anchor
// element inside the outer DIV
el[i].setAttribute('target', '_blank');
}
el_down.innerHTML = getAttr ();
}
</script>
</ body >
</ html >

Выход:

  • Перед нажатием на кнопку:
  • После нажатия на кнопку: